Completed
Pull Request — master (#366)
by Michael
08:55 queued 03:34
created

DefaultController::buildLicenseeIndex()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 0
crap 2
1
<?php
2
3
/* Copyright (C) 2015 Michael Giesler
4
 *
5
 * This file is part of Dembelo.
6
 *
7
 * Dembelo is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as published by
9
 * the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * Dembelo is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License 3 for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License 3
18
 * along with Dembelo. If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
22
/**
23
 * @package AdminBundle
24
 */
25
26
namespace AdminBundle\Controller;
27
28
use DembeloMain\Model\Repository\Doctrine\ODM\AbstractRepository;
29
use DembeloMain\Document\Importfile;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use StdClass;
35
use DembeloMain\Document\Topic;
36
use Symfony\Component\Serializer\Encoder\JsonEncoder;
37
38
/**
39
 * Class DefaultController
40
 */
41
class DefaultController extends Controller
42
{
43
44
    /**
45
     * @Route("/", name="admin_mainpage")
46
     *
47
     * @return Response
48
     */
49
    public function indexAction(): Response
50
    {
51
        $mainMenuData = [
52
            ['id' => '1', 'type' => 'folder', 'value' => 'Benutzer', 'css' => 'folder_music'],
53
            ['id' => '2', 'type' => 'folder', 'value' => 'Lizenznehmer', 'css' => 'folder_music'],
54
            ['id' => '3', 'type' => 'folder', 'value' => 'Themenfelder', 'css' => 'folder_music'],
55
            ['id' => '4', 'type' => 'folder', 'value' => 'Importe', 'css' => 'folder_music'],
56
            ['id' => '5', 'type' => 'folder', 'value' => 'Textknoten', 'css' => 'folder_music'],
57
        ];
58
59
        $jsonEncoder = new JsonEncoder();
60
61
        return $this->render('AdminBundle::index.html.twig', array('mainMenuData' => $jsonEncoder->encode($mainMenuData, 'json')));
62
    }
63
64
    /**
65
     * @Route("/users", name="admin_users")
66
     *
67
     * @param Request $request
68
     * @return Response
69
     */
70 2
    public function usersAction(Request $request): Response
71
    {
72 2
        $repository = $this->get('app.model_repository_user');
73
74 2
        $filters = $request->query->get('filter');
75
76 2
        $query = $repository->createQueryBuilder();
77 2
        if (null !== $filters) {
78 2 View Code Duplication
            foreach ($filters as $field => $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
                if (empty($value) && $value !== '0') {
80
                    continue;
81
                }
82
                if ($field === 'status') {
83
                    //$value = $value === 'aktiv' ? 1 : 0;
84
                    $query->field($field)->equals((int) $value);
85
                } else {
86
                    $query->field($field)->equals(new \MongoRegex('/.*'.$value.'.*/i'));
87
                }
88
            }
89
        }
90 2
        $users = $query->getQuery()->execute();
91
92 2
        $output = array();
93
        /* @var $user \DembeloMain\Document\User */
94 2
        foreach ($users as $user) {
95 1
            $obj = new StdClass();
96 1
            $obj->id = $user->getId();
97 1
            $obj->email = $user->getEmail();
98 1
            $obj->roles = implode(', ', $user->getRoles());
99 1
            $obj->licenseeId = is_null($user->getLicenseeId()) ? '' : $user->getLicenseeId();
100 1
            $obj->gender = $user->getGender();
101 1
            $obj->status = $user->getStatus(); // === 0 ? 'inaktiv' : 'aktiv';
102 1
            $obj->source = $user->getSource();
103 1
            $obj->reason = $user->getReason();
104 1
            $obj->created = date('Y-m-d H:i:s', $user->getMetadata()['created']);
105 1
            $obj->updated = date('Y-m-d H:i:s', $user->getMetadata()['updated']);
106 1
            $output[] = $obj;
107
        }
108
109 2
        return new Response(\json_encode($output));
110
    }
111
112
    /**
113
     * @Route("/licensees", name="admin_licensees")
114
     *
115
     * @return Response
116
     */
117 2 View Code Duplication
    public function licenseesAction(): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
    {
119 2
        $repository = $this->get('app.model_repository_licensee');
120
121 2
        $licensees = $repository->findAll();
122
123 2
        $output = array();
124
        /* @var $licensee \DembeloMain\Document\Licensee */
125 2
        foreach ($licensees as $licensee) {
126 1
            $obj = new StdClass();
127 1
            $obj->id = $licensee->getId();
128 1
            $obj->name = $licensee->getName();
129 1
            $output[] = $obj;
130
        }
131
132 2
        return new Response(\json_encode($output));
133
    }
134
135
    /**
136
     * @Route("/licenseeSuggest", name="admin_licensee_suggest")
137
     *
138
     * @param Request $request
139
     * @return Response
140
     */
141 View Code Duplication
    public function licenseeSuggestAction(Request $request): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
142
    {
143
        $filter = $request->query->get('filter');
144
145
        $searchString = $filter['value'];
146
147
        $mongo = $this->get('doctrine_mongodb');
148
        /* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
149
        $repository = $mongo->getRepository('DembeloMain:Licensee');
150
151
        $licensees = $repository->findBy(array('name' => new \MongoRegex('/'.$searchString.'/')), null, 10);
152
153
        $output = array();
154
        /* @var $licensee \DembeloMain\Document\Licensee */
155
        foreach ($licensees as $licensee) {
156
            $output[] = array(
157
                'id' => $licensee->getId(),
158
                'value' => $licensee->getName(),
159
            );
160
        }
161
162
        return new Response(\json_encode($output));
163
    }
164
165
    /**
166
     * @Route("/topicSuggest", name="admin_topic_suggest")
167
     *
168
     * @param Request $request
169
     * @return Response
170
     */
171 View Code Duplication
    public function topicSuggestAction(Request $request): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
172
    {
173
        $filter = $request->query->get('filter');
174
175
        $searchString = $filter['value'];
176
177
        $mongo = $this->get('doctrine_mongodb');
178
        /* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
179
        $repository = $mongo->getRepository('DembeloMain:Topic');
180
181
        /* @var $topics \DembeloMain\Document\Topic[] */
182
        $topics = $repository->findBy(array('name' => new \MongoRegex('/'.$searchString.'/')), null, 10);
183
184
        $output = [];
185
        foreach ($topics as $topic) {
186
            $output[] = array(
187
                'id' => $topic->getId(),
188
                'value' => $topic->getName(),
189
            );
190
        }
191
192
        return new Response(\json_encode($output));
193
    }
194
195
    /**
196
     * @Route("/topics", name="admin_topics")
197
     *
198
     * @return Response
199
     */
200 View Code Duplication
    public function topicsAction(): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
    {
202
        $mongo = $this->get('doctrine_mongodb');
203
        /* @var $repository \Doctrine\ODM\MongoDB\DocumentRepository */
204
        $repository = $mongo->getRepository('DembeloMain:Topic');
205
206
        $users = $repository->findAll();
207
208
        $output = array();
209
        /* @var $user \DembeloMain\Document\Topic */
210
        foreach ($users as $user) {
211
            $obj = new StdClass();
212
            $obj->id = $user->getId();
213
            $obj->name = $user->getName();
214
            $output[] = $obj;
215
        }
216
217
        return new Response(\json_encode($output));
218
    }
219
220
    /**
221
     * @Route("/save", name="admin_formsave")
222
     *
223
     * @param Request $request
224
     * @return Response
225
     */
226 5
    public function formsaveAction(Request $request): Response
227
    {
228 5
        $params = $request->request->all();
229
230 5
        if (!isset($params['formtype']) || !in_array($params['formtype'], array('user', 'licensee', 'topic', 'importfile', 'textnode'))) {
231 2
            return new Response(\json_encode(array('error' => true)));
232
        }
233 3
        if (!isset($params['id'])) {
234 1
            return new Response(\json_encode(array('error' => true)));
235
        }
236 2
        $formtype = $params['formtype'];
237
238
        /* @var $repository AbstractRepository */
239 2
        $repository = $this->get('app.model_repository_'.$formtype);
240
241 2
        if (isset($params['id']) && $params['id'] == 'new') {
242
            $className = $repository->getClassName();
243
            $item = new $className();
244
        } else {
245 2
            $item = $repository->find($params['id']);
246 2
            if (is_null($item) || $item->getId() != $params['id']) {
247 1
                return new Response(\json_encode(array('error' => true)));
248
            }
249
        }
250
251 1
        foreach ($params as $param => $value) {
252 1
            if (in_array($param, array('id', 'formtype', 'filename', 'orgname'))) {
253 1
                continue;
254
            }
255
            if ($param == 'password' && empty($value)) {
256
                continue;
257
            } elseif ($param == 'password') {
258
                $encoder = $this->get('security.password_encoder');
259
                $value = $encoder->encodePassword($item, $value);
260
            } elseif ($param == 'licenseeId' && $value === '') {
261
                $value = null;
262
            } elseif ($param === 'imported' && $value === '') {
263
                $value = null;
264
            }
265
            $method = 'set'.ucfirst($param);
266
            if (method_exists($item, $method)) {
267
                $item->$method($value);
268
            }
269
        }
270
        //var_dump($item);die();
271 1
        if (method_exists($item, 'setMetadata')) {
272 1
            $item->setMetadata('updated', time());
273
        }
274 1
        $repository->save($item);
275
276 1
        if ($formtype === 'topic' && array_key_exists('imageFileName', $params) && !is_null($params['imageFileName'])) {
277
            $this->saveTopicImage($item, $params['imageFileName'], $params['originalImageName']);
278
            $repository->save($item);
279
        }
280
281 1
        if ($formtype == 'importfile' && array_key_exists('filename', $params)) {
282
            $this->saveFile($item, $params['filename'], $params['orgname']);
283
            $repository->save($item);
284
        }
285
286
        $output = array(
287 1
            'error' => false,
288 1
            'newId' => $item->getId(),
289
        );
290
291 1
        return new Response(\json_encode($output));
292
    }
293
294
    /**
295
     * @Route("/useractivationmail", name="admin_user_activation_mail")
296
     *
297
     * @param Request $request
298
     * @return Response
299
     */
300
    public function useractivationmailAction(Request $request): Response
301
    {
302
        $userId = $request->request->get('userId');
303
304
        /* @var $mongo \Doctrine\Bundle\MongoDBBundle\ManagerRegistry */
305
        $mongo = $this->get('doctrine_mongodb');
306
        /* @var $dm \Doctrine\ODM\MongoDB\DocumentManager*/
307
        $dm = $mongo->getManager();
308
309
        $repository = $mongo->getRepository('DembeloMain:User');
310
311
        /* @var $user \DembeloMain\Document\User */
312
        $user = $repository->find($userId);
313
        if (null === $user) {
314
            return new Response(\json_encode(['error' => false]));
315
        }
316
        $user->setActivationHash(sha1($user->getEmail().$user->getPassword().\time()));
317
318
        $dm->persist($user);
319
        $dm->flush();
320
321
        $message = (new \Swift_Message('waszulesen - Bestätigung der Email-Adresse'))
322
            ->setFrom('[email protected]')
323
            ->setTo($user->getEmail())
324
            ->setBody(
325
                $this->renderView(
326
                    // app/Resources/views/Emails/registration.html.twig
327
                    'AdminBundle::Emails/registration.txt.twig',
328
                    array('hash' => $user->getActivationHash())
329
                ),
330
                'text/html'
331
            );
332
333
        $this->get('mailer')->send($message);
334
335
        return new Response(\json_encode(['error' => false]));
336
    }
337
338
    /**
339
     * @Route("/textnodes", name="admin_textnodes")
340
     *
341
     * @return Response
342
     */
343 1
    public function textnodesAction(): Response
344
    {
345 1
        $repository = $this->get('app.model_repository_textNode');
346 1
        $textnodes = $repository->findAll();
347
348 1
        $licenseeIndex = $this->buildLicenseeIndex();
349 1
        $importfileIndex = $this->buildImportfileIndex();
350
351 1
        $output = array();
352
        /* @var $textnode \DembeloMain\Document\Textnode */
353 1
        foreach ($textnodes as $textnode) {
354 1
            $obj = new StdClass();
355 1
            $obj->id = $textnode->getId();
356 1
            $obj->arbitraryId = $textnode->getArbitraryId();
357 1
            $obj->created = $textnode->getCreated()->format('d.m.Y, H:i:s');
358 1
            $obj->status = $textnode->getStatus() ? 'aktiv' : 'inaktiv';
359 1
            $obj->access = $textnode->getAccess() ? 'ja' : 'nein';
360 1
            $obj->licensee = $licenseeIndex[$textnode->getLicenseeId()];
361 1
            $obj->importfile = isset($importfileIndex[$textnode->getImportfileId()]) ? $importfileIndex[$textnode->getImportfileId()] : 'unbekannt';
362 1
            $obj->beginning = substr(htmlentities(strip_tags($textnode->getText())), 0, 200)."...";
363 1
            $obj->financenode = $textnode->isFinanceNode() ? 'ja' : 'nein';
364 1
            $obj->twineId = $textnode->getTwineId();
365 1
            $obj->metadata = $this->formatMetadata($textnode->getMetadata());
366 1
            $output[] = $obj;
367
        }
368
369 1
        return new Response(\json_encode($output));
370
    }
371
372
    /**
373
     * saves temporary file to final place
374
     *
375
     * @param Importfile $item importfile instance
376
     * @param string $filename filename hash
377
     * @param string $orgname original name
378
     */
379 View Code Duplication
    private function saveFile(Importfile $item, $filename, $orgname)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
380
    {
381
        if (empty($filename) || empty($orgname)) {
382
            return;
383
        }
384
385
        $directory = $this->container->getParameter('twine_directory');
386
        $finalDirectory = $directory.$item->getLicenseeId().'/';
387
        if (!is_dir($finalDirectory)) {
388
            mkdir($finalDirectory);
389
        }
390
        $finalName = $finalDirectory.$item->getId();
391
        $file = $directory.$filename;
392
        rename($file, $finalName);
393
394
        $item->setOriginalname($orgname);
395
        $item->setFilename($finalName);
396
    }
397
398 1
    private function buildLicenseeIndex(): array
399
    {
400 1
        $repository = $this->get('app.model_repository_licensee');
401 1
        $licensees = $repository->findAll();
402 1
        $index = [];
403 1
        foreach ($licensees as $licensee) {
404 1
            $index[$licensee->getID()] = $licensee->getName();
405
        }
406
407 1
        return $index;
408
    }
409
410 1
    private function buildImportfileIndex(): array
411
    {
412 1
        $repository = $this->get('app.model_repository_importfile');
413 1
        $importfiles = $repository->findAll();
414 1
        $index = [];
415 1
        foreach ($importfiles as $importfile) {
416 1
            $index[$importfile->getID()] = $importfile->getName();
417
        }
418
419 1
        return $index;
420
    }
421
422
    /**
423
     * saves temporary file to final place
424
     *
425
     * @param Topic $item topic instance
426
     * @param string $filename filename hash
427
     * @param string $orgname original name
428
     */
429 View Code Duplication
    private function saveTopicImage(Topic $item, $filename, $orgname)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
430
    {
431
        if (empty($filename) || empty($orgname)) {
432
            return;
433
        }
434
        $directory = $this->container->getParameter('topic_image_directory');
435
        $finalDirectory = $directory.$item->getId().'/';
436
        if (!is_dir($finalDirectory)) {
437
            mkdir($finalDirectory);
438
        }
439
        $finalName = $finalDirectory.$orgname;
440
        $file = $directory.$filename;
441
        rename($file, $finalName);
442
        $item->setOriginalImageName($orgname);
443
        $item->setImageFilename($finalName);
444
    }
445
446 1
    private function formatMetadata(array $metadata): string
447
    {
448 1
        $string = '';
449 1
        foreach ($metadata as $key => $value) {
450 1
            $string .= $key.': '.$value."\n";
451
        }
452
453 1
        return $string;
454
    }
455
}
456