UsersController.php 60.6 KB
Newer Older
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
1
<?php
2
3
4
5
6
7
8
/**
 * Controller Of Users.
 *
 * @package App\Controller\Api\V1
 * @author  mickael pastor <mickael.pastor@adullact.org>
 * @license https://spdx.org/licenses/AGPL-3.0-or-later.html Affero General Public License
 */
9

10
namespace App\Controller\Api\V1;
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
11
12

use App\Controller\AppController;
13
use App\Controller\Component\RulesComponent;
14
use App\Model\Entity\User;
15
use App\Model\Table\UsersTable;
Matthieu FAURE's avatar
Matthieu FAURE committed
16
use Cake\Core\Configure;
17
use Cake\Event\Event;
18
use Cake\Mailer\MailerAwareTrait;
19
20
use Cake\Network\Exception\NotFoundException;
use Cake\Network\Response;
21
use Cake\ORM\Query;
Pastor Mickaël's avatar
Pastor Mickaël committed
22
use Cake\Utility\Text;
23
use Cake\Filesystem\Folder;
24

Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
25
26
27
/**
 * Users Controller
 *
28
 * @property UsersTable $Users
29
30
31
 * @package  App\Controller\Api\V1
 * @author   mickael pastor <mickael.pastor@adullact.org>
 * @license  https://spdx.org/licenses/AGPL-3.0-or-later.html Affero General Public License
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
32
33
34
 */
class UsersController extends AppController
{
35
    use MailerAwareTrait;
Pastor Mickaël's avatar
Pastor Mickaël committed
36

37
38
39
40
41
42
    /**
     * How long the token is valid
     * to change the password (in number of hours)
     */
    const TOKEN_VALIDITY_TIME_TO_CHANGE_PASSWORD = '24'; // 24 hours

Pastor Mickaël's avatar
Pastor Mickaël committed
43
44
    /**
     * Manage all rights for the controllers' actions.
45
     * Returns true if the user can use the current action, FALSE otherwise.
Pastor Mickaël's avatar
Pastor Mickaël committed
46
47
     * Returns true for add a project if the user is connected
     * Returns true for edit and delete action if the user is owner.
48
49
     *
     *
Matthieu FAURE's avatar
Matthieu FAURE committed
50
     * notice: $forceDeny parameter is mandatory to be compatible with parent::isAuthorized()
51
52
53
54
     *                     and it's forced to TRUE
     *
     * @param array $user A user.
     * @param  boolean $forceDeny by default FALSE, set TRUE to force the deny on parent::isAuthorized()
Pastor Mickaël's avatar
Pastor Mickaël committed
55
56
     * @return boolean
     */
57
    public function isAuthorized($user, $forceDeny = false)
Pastor Mickaël's avatar
Pastor Mickaël committed
58
    {
59

Matthieu FAURE's avatar
Matthieu FAURE committed
60
        // Access to edit method only for the current user
61
        $forceDeny = false;
62
63
        if ($this->request->param('action') === 'edit') {
            if ($this->Auth->user('id') == $this->request->params["pass"][0]) {
Pastor Mickaël's avatar
Pastor Mickaël committed
64
65
                return true;
            }
66
67
68
            // GET requests is not allowed, if the user tries to edit another user's record
            // ----> force the deny on parent::isAuthorized()
            $forceDeny = true;
69
        }
Pastor Mickaël's avatar
Pastor Mickaël committed
70

71
72
        // Access to contact method
        if ($this->request->param('action') === 'contact') {
73
            // Allow access to all users except providers
74
75
            $notAllowedUserTypeId = $this->getUserTypeIdByName('Company');
            if ($this->Auth->user('user_type_id') !== $notAllowedUserTypeId) {
76
                return true;
77
            } else { // if a provider (user_type = 'Company') tries to contact another user
78
79
80
                $forceDeny = true; // force the deny on parent::isAuthorized() for GET request
                                   // by default POST request are deny on parent::isAuthorized()
            }
81
82
        }

83
84
85
86
87
88
89
        // Access to "export" method
        if ($this->request->param('action') === 'export') {
            // only user with "admin" role can use "export" action --> see: parent::isAuthorized()
            $forceDeny = true;  // force the deny on parent::isAuthorized() for GET request
                                // by default POST request are deny on parent::isAuthorized()
        }

90
        if ($this->request->param('action') === 'changePassword') {
91
92
            $tokenOrId = $this->request->params["pass"][0];

93
            $user = $this->Users->findById($tokenOrId, ["contain" => []])->first();
Pastor Mickaël's avatar
Pastor Mickaël committed
94

Matthieu FAURE's avatar
Matthieu FAURE committed
95
96
97
98
            if ($this->Auth->user('id') == $user->id || $this->Users->findByToken(
                $tokenOrId,
                ["contain" => []]
            )->first()) {
Pastor Mickaël's avatar
Pastor Mickaël committed
99
100
101
102
                return true;
            }
        }

Pastor Mickaël's avatar
Pastor Mickaël committed
103
        //If user is auth
104
105
        if ($this->request->param('action') === 'register') {
            if ($user) {
Pastor Mickaël's avatar
Pastor Mickaël committed
106
107
108
                return true;
            }
        }
109
        return parent::isAuthorized($user, $forceDeny);
Pastor Mickaël's avatar
Pastor Mickaël committed
110
111
    }

112
113
114
115
116
    /**
     * Initialisation of a user
     *
     * @return void
     */
117
118
    public function initialize()
    {
Pastor Mickaël's avatar
Pastor Mickaël committed
119
120
121
        parent::initialize();
        $this->paginate = [
            'limit' => Configure::read('LIMIT'),
122
            'maxLimit' => Configure::read('LIMIT'),
Pastor Mickaël's avatar
Pastor Mickaël committed
123
124
125
            'order' => [
                'Users.username' => Configure::read('ORDER'),
            ],
Pastor Mickaël's avatar
Pastor Mickaël committed
126
            'fields' => [
Matthieu FAURE's avatar
Matthieu FAURE committed
127
128
129
130
131
132
133
134
135
                'id',
                'username',
                'email',
                'user_type_id',
                'url',
                'description',
                'photo',
                'logo_directory',
                'UserTypes.name'
Pastor Mickaël's avatar
Pastor Mickaël committed
136
            ],
Pastor Mickaël's avatar
Pastor Mickaël committed
137
138
139
140
            'contain' => ['UserTypes']
        ];
    }

Fabrice Gangler's avatar
Fabrice Gangler committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

    /**
     * $links = [ 0 => [ 'name' => '…', 'url' => '/dir/file', 'title' => '…'],
     *            1 => [ 'name' => '…', 'url' => '/dir/file', 'title' => '…'], ]
     *
     * @param array $links
     */
    protected function setBreadcrumbs(array $links = [])
    {
        $firstLink = [
            'name' => __d('Breadcrumbs', 'User.ListOfUsers'),
            'url' => 'users'
        ];
        array_unshift($links, $firstLink);
        parent::setBreadcrumbs($links);
    }

    /**
     * $links = [ 0 => [ 'name' => '…', 'url' => '/dir/file', 'title' => '…'],
     *            1 => [ 'name' => '…', 'url' => '/dir/file', 'title' => '…'], ]
     *
     * @param array $links
     */
    protected function setBreadcrumbsUser(array $links = [], $user = null)
    {

        if (is_object($user) and $user->user_type->name === 'Company') {
            $firstLink = [
                'name' => __d('Breadcrumbs', 'Users.Providers'),
                'url' => "users/providers"
            ];
        } else {
            $firstLink = [
                'name' => __d('Breadcrumbs', 'User.ListOfUsers'),
                'url' => 'users'
            ];
        }
        array_unshift($links, $firstLink);
        parent::setBreadcrumbs($links);
    }


Pastor Mickaël's avatar
Pastor Mickaël committed
183
    /**
184
     * Allow = actions allow without being connected
185
186
     * Before filter manage right access of users
     *
187
     * @param Event $event Events
188
189
     *
     * @return void
Pastor Mickaël's avatar
Pastor Mickaël committed
190
     */
191
    public function beforeFilter(Event $event)
Pastor Mickaël's avatar
Pastor Mickaël committed
192
    {
193
194
        $this->Auth->allow(
            [
Matthieu FAURE's avatar
Matthieu FAURE committed
195
196
197
198
199
                'add',
                'providers',
                'administrations',
                'nonProfitUsers',
                'providerforSoftwares',
200
                'reviewsforSoftware',
Matthieu FAURE's avatar
Matthieu FAURE committed
201
202
203
                'usedSoftwares',
                'forgotPassword',
                'changePassword',
204
205
206
                'resetPassword',
            ]
        );
207
        $this->Auth->deny(['delete', 'edit', 'register', 'contact']);
208

Pastor Mickaël's avatar
Pastor Mickaël committed
209
210
211
        parent::beforeFilter($event);
    }

Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
212
    /**
Julie gauthier's avatar
Julie gauthier committed
213
214
215
216
217
     * Returns a list of users.
     *
     * Note: whereas service providers are part of the User entity in the database, they are not considered as a user
     *   from the application point of view. They have their dedicated "identity". Maybe one day, they'll be extracted
     *   as a separated entity in the DB schema.
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
218
219
220
221
222
     *
     * @return void
     */
    public function index()
    {
Julie gauthier's avatar
Julie gauthier committed
223
224
225
        if (!empty($this->request->query)
            && isset($this->request->query["order"])
        ) {
226
            $sort = explode(".", $this->request->query["order"]);
Fabrice Gangler's avatar
Fabrice Gangler committed
227
228
            // Note JGauthier 2019-07-16: just discovered this horror. This is not the correct way to do this.
            // TODO This should be fixed
229
230
231
232
            $this->request->query["sort"] = $sort[0];
            $this->request->query["direction"] = $sort[1];
        }

233
        $users = $this->Users
234
235
            ->find(
                'search',
236
                [
237
238
239
240
241
242
                    'sortWhitelist' => [
                        'username',
                        'average_review',
                        'created',
                        'modified',
                    ],
243
244
                    'search' => $this->request->query,
                    'contain' => ['UserTypes'],
Julie gauthier's avatar
Julie gauthier committed
245
                    'order' =>
246
                        isset($this->request->query["sort"])
Julie gauthier's avatar
Julie gauthier committed
247
248
249
250
251
                        && isset($this->request->query["direction"])
                            ?
                            ['Users.' . $this->request->query["sort"] => $this->request->query["direction"]]
                            :
                            ['Users.username' => Configure::read('ORDER')]
252
                    ,
Julie gauthier's avatar
Julie gauthier committed
253
                ]
254
255
            )
            ->where(["UserTypes.cd <> " => "Company"]);
256

257
        //For filters
258
        $hadReview = [
259
260
            "false" => __d("Forms", "Search.Filter.Users.NoFilterOnReview"),
            "true" => __d("Forms", "Search.Filter.Users.WithReview"),
261
262
263
        ];

        $userType = [
264
265
266
267
            "all" => __d("Forms", "Search.Filter.Users.NoFilterOnUserType"),
            "Administration" => __d("Forms", "Search.Filter.Users.userTpye.Administration"),
            "Person" => __d("Forms", "Search.Filter.Users.userTpye.Person"),
            "Association" => __d("Forms", "Search.Filter.Users.userTpye.Association"),
268
269
270
        ];

        $isUserOf = [
271
272
            "false" => __d("Forms", "Search.Filter.Users.NoFilterOnIsUserOf"),
            "true" => __d("Forms", "Search.Filter.Users.IsUserOf"),
273
274
        ];

Matthieu FAURE's avatar
Matthieu FAURE committed
275
        $isServiceProvider = [
276
277
            "false" => __d("Forms", "Search.Filter.Users.NoFilterOnIsServicesProvider"),
            "true" => __d("Forms", "Search.Filter.Users.IsServicesProvider"),
278
279
280
        ];

        $order = [
281
282
283
284
285
286
            "username.asc" => __d("Forms", "Search.Sort.usernameAsc"),
            "username.desc" => __d("Forms", "Search.Sort.usernameDesc"),
            "created.asc" => __d("Forms", "Search.Sort.createdAsc"),
            "created.desc" => __d("Forms", "Search.Sort.createdDesc"),
            "modified.asc" => __d("Forms", "Search.Sort.modifiedAsc"),
            "modified.desc" => __d("Forms", "Search.Sort.modifiedDesc"),
287
        ];
288
        //End For filters
289
290
291
292
293

        $this->set('hadReview', $hadReview);
        $this->set('userType', $userType);
        $this->set('isUserOf', $isUserOf);
        $this->set('order', $order);
Matthieu FAURE's avatar
Matthieu FAURE committed
294
        $this->set('isServiceProvider', $isServiceProvider);
295

296
297
        $this->set(
            [
Matthieu FAURE's avatar
Matthieu FAURE committed
298
299
                'users' => $this->paginate($users),
                '_serialize' => ['users']
Julie gauthier's avatar
Julie gauthier committed
300
301
            ]
        );
Fabrice Gangler's avatar
Fabrice Gangler committed
302
        $this->setBreadcrumbs();
303
304
    }

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
    /**
     * Export method
     *
     * @return void
     */
    public function export()
    {
        $this->request->allowMethod(['get']);

        ////////////////////////////////////////////////////////////
        // Retrieve data from database
        ////////////////////////////////////////////////////////////
        $this->paginate = [
            "Users" => [
                'sortWhitelist' => [
                    'username'
                ],

                'limit' => Configure::read('LIMIT'),
                'maxLimit' => Configure::read('LIMIT'),
                'order' => ['username' => Configure::read('ORDER')],
            ]
        ];

        $users = $this->Users
            ->find(
                'search',
                [
                    'sortWhitelist' => [
                        'username',
                        'average_review',
                        'created',
                        'modified',
                    ],
                    'search' => $this->request->query,
                    'contain' => [
                        'UserTypes',
                        'Reviews' => [
                            'strategy' => 'select',
                            'queryBuilder' => function ($q) {
                                return $q->order(['Reviews.created' => 'ASC']);
                            },
                            'Softwares' => [
                                'fields' => [
                                    'id',
                                    'softwarename',
                                    'logo_directory',
                                    'photo',
                                ]
                            ]
                        ],
                        'Usedsoftwares' => [
                            'strategy' => 'select',
                            'queryBuilder' => function (Query $q) {
                                return $q->order(['Softwares.softwarename' => 'ASC']);
                            },
                            'Softwares' => [
                                'Reviews' => [
                                ],
                                'fields' => [
                                    'id',
                                    'softwarename',
                                    'logo_directory',
                                    'photo',
                                    'description',
                                ]
                            ]
                        ],
                        "Providerforsoftwares" => [
                            'strategy' => 'select',
                            'queryBuilder' => function ($q) {
                                return $q->order(['Softwares.softwarename' => 'ASC']);
                            },
                            'Softwares' => [
                                'Reviews' => [
                                ],
                                'fields' => [
                                    'id',
                                    'softwarename',
                                    'logo_directory',
                                    'photo',
                                    'description'
                                ]
                            ],
                        ],
                    ],
                    'order' =>   ['UserTypes.cd'=> 'ASC', 'Users.username' => 'ASC'],
                ]
            );

        ////////////////////////////////////////////////////////////
        // Generate CSV ans JSON exports
        ////////////////////////////////////////////////////////////
        $data = [
            'date_of_export' => date(DATE_ATOM),
            'number_of_users' => $users->count(),
            'users' => []
        ];
        $csvData  = '';
        foreach ($this->paginate($users) as $user) {
            $lastUserUpdate = $user->modified;

            // Provider
            $providedForSoftwareUrl = '';
            $lastProvidedForSoftware = '';
            $providedForSoftwares = [];
            $providedForSoftwareNumber = count($user->providerforsoftwares);
            if ($providedForSoftwareNumber > 0) {
                $providedForSoftwareUrl =  'https://comptoir-du-libre.org/fr/users/providerforSoftwares/'. $user->id ;
            }
            foreach ($user->providerforsoftwares as $providedSoftware) {
                if ($lastUserUpdate < $providedSoftware->created) {
                    $lastUserUpdate = $providedSoftware->created;
                }
                if (empty($lastProvidedForSoftware) || $lastProvidedForSoftware < $providedSoftware->created) {
                    $lastProvidedForSoftware = $providedSoftware->created;
                }
                $providedForSoftwares[] = [
                    'created' => $providedSoftware->created,
                    'software' => $providedSoftware->software->softwarename,
                    'software_id' => $providedSoftware->software->id,
                    'software_url' => 'http://localhost:8282/fr/softwares/'.$providedSoftware->software->id,
                ];
            }

            // Review
            ////////////////////////////////////////////////////////////////////
            $reviewUrl = '';
            $lastReview = '';
            $reviews = [];
            $reviewNumber = count($user->reviews);
            if ($reviewNumber > 0) {
                $reviewUrl =  'https://comptoir-du-libre.org/fr/users/'. $user->id .'/reviews';
            }
            foreach ($user->reviews as $review) {
                if ($lastUserUpdate < $review->created) {
                    $lastUserUpdate = $review->created;
                }
                if (empty($lastReview) || $lastReview < $review->created) {
                    $lastReview = $review->created;
                }
                $review_url = 'http://localhost:8282/fr/softwares/'.$review->software->id.'/reviews/' . $review->id;
                $reviews[] = [
                    'review_id' => $review->id,
                    'review_url' => $review_url,
                    'review_created' => $review->created,
                    'software' => $review->software->softwarename,
                    'software_id' => $review->software->id,
                    'software_url' => 'http://localhost:8282/fr/softwares/'.$review->software->id,
                ];
            }

            // User of
            ////////////////////////////////////////////////////////////////////
            $usedSoftwareUrl = '';
            $lastUsedSoftware = '';
            $usedSoftwares = [];
            $usedSoftwareNumber = count($user->usedsoftwares);
            if ($usedSoftwareNumber > 0) {
                $usedSoftwareUrl =  'https://comptoir-du-libre.org/fr/users/usedSoftwares/'. $user->id ;
            }
            foreach ($user->usedsoftwares as $usedsoftware) {
                if ($lastUserUpdate < $usedsoftware->created) {
                    $lastUserUpdate = $usedsoftware->created;
                }
                if (empty($lastUsedSoftware) || $lastUsedSoftware < $usedsoftware->created) {
                    $lastUsedSoftware = $usedsoftware->created;
                }
                $usedSoftwares[] = [
                    'created' => $usedsoftware->created,
                    'software' => $usedsoftware->software->softwarename,
                    'software_id' => $usedsoftware->software->id,
                    'software_url' => 'http://localhost:8282/fr/softwares/'.$usedsoftware->software->id,
                ];
            }

            // JSON data
            $item = [
                'id' => $user->id,
                'created' => $user->created,
                'modified' => $lastUserUpdate,
                'url' => 'https://comptoir-du-libre.org/fr/users/'. $user->id,
                'name' => $user->username,
                'user_type' => $user->user_type->cd,
                'external_resources' => [
                    'website' => $user->url,
                ],
                'reviews' => [
                    'number'   => $reviewNumber,
                    'last'     => $lastReview,
                    'url'     => $reviewUrl,
                    'software'  => $reviews,
                ],
                'usingSoftware' => [
                    'number'   => $usedSoftwareNumber,
                    'last'     => $lastUsedSoftware,
                    'url'     => $usedSoftwareUrl,
                    'software'  => $usedSoftwares,
                ],
                'providingSoftware' => [
                    'number'   => $providedForSoftwareNumber,
                    'last'     => $lastProvidedForSoftware,
                    'url'     => $providedForSoftwareUrl,
                    'software'  => $providedForSoftwares,
                ],
            ];
            $data['users'][] = $item;

            // CSV data
            if ($reviewNumber === 0) {
                $reviewNumber = '';
            }
            if ($usedSoftwareNumber === 0) {
                $usedSoftwareNumber = '';
            }
            if ($providedForSoftwareNumber === 0) {
                $providedForSoftwareNumber = '';
            }
523
            $csvData .= ''.  $user->id                  .';';
524
525
526
527
528
529
530
531
532
533
534
535
536
            $csvData .= '"'. $user->user_type->cd       .'";';
            $csvData .= '"'. $user->username            .'";';
            $csvData .= '' . $user->created             .';';
            $csvData .= '' . $lastUserUpdate            .';';
            $csvData .= ''. $reviewNumber               .';';
            $csvData .= ''. $usedSoftwareNumber         .';';
            $csvData .= ''. $providedForSoftwareNumber  .';';
            $csvData .= '' . $lastReview                .';';
            $csvData .= '' . $lastUsedSoftware          .';';
            $csvData .= '' . $lastProvidedForSoftware   .';';
            $csvData .= "\n";
        }
        $csvHead = '';
537
        $csvHead .= "\"id\";";
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
        $csvHead .= "\"type\";";
        $csvHead .= "\"name\";";
        $csvHead .= "\"created\";";
        $csvHead .= "\"modified\";";
        $csvHead .= "\"reviews\";";
        $csvHead .= "\"using software\";";
        $csvHead .= "\"providing software\";";
        $csvHead .= "\"last review\";";
        $csvHead .= "\"last using software\";";
        $csvHead .= "\"last providing software\";";
        $csvHead .= "\n";
        $csv = $csvHead . $csvData;

        // Clean export directory
        $folder = new Folder('public/export/users/temporary');
        $folder->delete();

        // Create a new temporary directory
        $aleaBytes = \openssl_random_pseudo_bytes(40);
        $aleaHex   = bin2hex($aleaBytes);
        $exportPath = "public/export/users/temporary/tmp_$aleaHex/" ;
        \mkdir("$exportPath", 0744, true);

        // Save export files
        $exportDate = date('Y.m.d_H\hi.s');
        $json = \json_encode($data, JSON_PRETTY_PRINT);
        $exportFileName = "comptoir-du-libre_users_$exportDate";
        $exportJsonFileName = "$exportFileName.json";
        $exportCsvFileName = "$exportFileName.csv";
        $exportJsonFilePath = $exportPath . $exportJsonFileName;
        $exportCsvFilePath = $exportPath  . $exportCsvFileName;
        if (is_dir(WWW_ROOT . $exportPath)) {
            file_put_contents(WWW_ROOT . $exportJsonFilePath, "$json");
            file_put_contents(WWW_ROOT . $exportCsvFilePath, "$csv");
            $this->set('exportJsonFileName', "$exportJsonFileName");
            $this->set('exportCsvFileName', "$exportCsvFileName");
            $this->set('exportJsonFilePath', "$exportJsonFilePath");
            $this->set('exportCsvFilePath', "$exportCsvFilePath");
            $this->set('exportJson', file_get_contents(WWW_ROOT . $exportJsonFilePath));
            $this->set('exportCsv', file_get_contents(WWW_ROOT . $exportCsvFilePath));
        }
    }




Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
584
585
586
587
    /**
     * View method
     *
     * @param string|null $id User id.
588
589
     *
     * @return void
590
591
     * @throws NotFoundException When record not found.
     *
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
592
593
594
     */
    public function view($id = null)
    {
595
        $user = $this->Users->get(
596
597
            $id,
            [
Matthieu FAURE's avatar
Matthieu FAURE committed
598
599
600
601
602
603
604
605
606
607
608
609
610
611
                'contain' => [
                    'UserTypes',
                    'Reviews' => [
                        'strategy' => 'select',
                        'queryBuilder' => function ($q) {
                            return $q->order(['Reviews.created' => 'DESC']);
                        },
                        'Softwares' => [
                            'fields' => [
                                'id',
                                'softwarename',
                                'logo_directory',
                                'photo',
                            ]
612
                        ]
Matthieu FAURE's avatar
Matthieu FAURE committed
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
                    ],
                    'Usedsoftwares' => [
                        'strategy' => 'select',
                        'queryBuilder' => function (Query $q) {
                            return $q->order(['Softwares.softwarename' => 'ASC']);
                        },
                        'Softwares' => [
                            'Reviews' => [
                            ],
                            'fields' => [
                                'id',
                                'softwarename',
                                'logo_directory',
                                'photo',
                                'description',
                            ]
629
                        ]
Matthieu FAURE's avatar
Matthieu FAURE committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
                    ],
                    "Providerforsoftwares" => [
                        'strategy' => 'select',
                        'queryBuilder' => function ($q) {
                            return $q->order(['Softwares.softwarename' => 'ASC']);
                        },
                        'Softwares' => [
                            'Reviews' => [
                            ],
                            'fields' => [
                                'id',
                                'softwarename',
                                'logo_directory',
                                'photo',
                                'description'
                            ]
646
                        ],
647
                    ],
Matthieu FAURE's avatar
Matthieu FAURE committed
648
                ]
649
650
            ]
        );
651

652
653
654
655
656
657
658
        // Check that the current URL is correct
        $lang = $this->selectedLanguage;
        $allowedUrl = "/$lang/users/". (int) $id;
        if ($allowedUrl !== $this->request->here(false) && !$this->request->is('json')) {
            return $this->redirect("$allowedUrl", 301);
        }

659
        // Load mapping data if available for current user and populate view data
660
        $this->commonMappingForUser($user);
661

662
663
        //For Social MEDIAS => OPENGRAPH
        $openGraph = [
664
            "title" => $user->username,
665
            "description" => $user->description,
666
            "image" => Configure::read('App.fullBaseUrl') . DS . $user->logo_directory . DS . $user->photo,
667
668
669
670
            "imageSize" => ['width' => '200', 'height' => '300']
        ];

        $card = [
671
            "title" => $user->username,
672
            "description" => $user->description,
673
            "image" => Configure::read('App.fullBaseUrl') . DS . $user->logo_directory . DS . $user->photo,
674
675
676
677
678
679
            "imageSize" => ['width' => '200', 'height' => '300']
        ];

        $this->set('openGraph', $openGraph);
        $this->set('card', $card);

680
        $this->set(compact('user'));
681
        $this->set('_serialize', ['user']);
Fabrice Gangler's avatar
Fabrice Gangler committed
682
683
684
685
686
687
688
689

        // Breadcrumbs
        $links = array();
        $links[] = [
            'name' => $user->username,
            'url' => "users/".$user->id
        ];
        $this->setBreadcrumbsUser($links, $user);
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
690
691
    }

692
693
    /**
     * Load mapping data if available for given user ID and populate view data
694
     * @param User $user
695
     */
696
    protected function commonMappingForUser(User $user)
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
    {
        $data = $this->getMappingForUser($user);
        $taxonomiesSoftware = $data['taxonomiesSoftware'];
        $usedSoftwareKeys = $data['usedSoftwareKeys'];
        $mappingFirstLevels = $data['mappingFirstLevels'];
        $mappingTaxons = $data['mappingTaxons'];

        // Populate view data
        $this->set(compact(['mappingFirstLevels']));
        $this->set(compact(['mappingTaxons']));
        $this->set(compact(['usedSoftwareKeys']));
        $this->set(compact(['taxonomiesSoftware']));
        $this->set('_serialize', [
            'taxonomiesSoftware',
            'usedSoftwareKeys',
            'mappingTaxons',
            'mappingFirstLevels'
        ]);
    }


    /**
     * Load mapping data if available for given user ID
     * and return a array of all software declared by user for one or multiple taxon
     *
     * @param User $user
     * @return array   example: [
     *                   'LibreOffice' => ['softwareName' => 'LibreOffice',
     *                                     'softwareId'   => 33,
     *                                     'modified'     => '2022-06-01T11:05:53+00:00',
     *                                     'mappingTaxons' => [['slug' => 'bureautique', 'title' => 'Bureautique],]]
     */
    protected function getSofwareMappingForUser(User $user)
    {
        $mappingData = $this->getMappingForUser($user);
        $softwareDeclaredInTaxonomy = [];
        if (count($mappingData['taxonomiesSoftware']) > 0) {
            foreach ($mappingData['taxonomiesSoftware'] as $taxon) {
                foreach ($taxon as $softwareName => $taxonData) {
                    $taxonomyId = $taxonData->taxonomy_id;
                    $mappingTaxons = $mappingData['mappingTaxons'][$taxonomyId];
                    $softwareDeclaredInTaxonomy[$softwareName]['softwareName'] = $softwareName;
                    $softwareDeclaredInTaxonomy[$softwareName]['softwareId'] = $taxonData->software_id;
                    $softwareDeclaredInTaxonomy[$softwareName]['mappingTaxons'][$taxonomyId] =$mappingTaxons;
                    $modified = $taxonData['modified']; // Cake\I18n\Time
                    if (!isset($softwareDeclaredInTaxonomy[$softwareName]['modified'])) {
                        $softwareDeclaredInTaxonomy[$softwareName]['modified'] = $modified; // Cake\I18n\Time
                    } elseif ($softwareDeclaredInTaxonomy[$softwareName]['modified']  < $modified) {
                        $softwareDeclaredInTaxonomy[$softwareName]['modified'] = $modified; // Cake\I18n\Time
                    }
                }
            }
        }
        return $softwareDeclaredInTaxonomy;
    }


    /**
     * Load mapping data if available for given user ID
     *
     * @param User $user
     * @return array
     */
    protected function getMappingForUser(User $user)
761
    {
762
763
        $taxonomiesSoftware = [];
        $usedSoftwareKeys = [];
764
765
        $mappingFirstLevels = [];
        $mappingTaxons = [];
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801

        $userId = $user->id;
        if ($user->isAdministrationType() && count($user->usedsoftwares) > 0) {
            // Get taxonomy records grouped by taxon ID for this user
            $this->loadModel("TaxonomysSoftwares");
            $taxonomiesSoftware = $this->TaxonomysSoftwares->getListByUserId($userId);

            // Load mapping data if necessary
            $mappingFirstLevels = [];
            $mappingTaxons = [];
            if (count($taxonomiesSoftware) > 0) {
                // Load mapping data
                $taxonIds = array_keys($taxonomiesSoftware);
                $mappingFirstLevels = $this->getMappingFirstLevels($this->selectedLanguage);
                $mappingTaxons = $this->getMappingTaxonsWithTaxonIdsFilter($taxonIds, $this->selectedLanguage);

                // Extract used software keys and software names
                $softwareNameList = [];
                foreach ($user->usedsoftwares as $usedSoftwareKey => $usedSoftware) {
                    $softwareId = $usedSoftware->software->id;
                    $softwareNameList[$softwareId] = $usedSoftware->software->softwarename;
                    $usedSoftwareKeys[$softwareId] = $usedSoftwareKey;
                }

                // Sort records by software name
                foreach ($taxonomiesSoftware as $taxonId => $taxonData) {
                    $taxonDataSorted = [];
                    foreach ($taxonData as $item) {
                        $softwareId = $item->software_id;
                        $softwareName = $softwareNameList[$softwareId];
                        $taxonDataSorted[$softwareName] = $item;
                    }
                    ksort($taxonDataSorted);
                    $taxonomiesSoftware[$taxonId] = $taxonDataSorted;
                }
            }
802
        }
803
804
805
806
807
808
        return [
            'taxonomiesSoftware' => $taxonomiesSoftware,
            'usedSoftwareKeys' => $usedSoftwareKeys,
            'mappingFirstLevels' => $mappingFirstLevels,
            'mappingTaxons' => $mappingTaxons,
        ];
809
810
811
    }


812
813
814
815
816
817
818

    /**
     * Tooling for "add" method: create anti-spam tokens
     * - create anti-spam tokens (get, post, form)
     * - save tokens in user session
     * - return token for HTTP GET method
     *
819
     * @param false $cleanBeforeCreateTokens
820
821
     * @return string token for HTTP GET method
     */
822
    private function addUserCreateTokens($cleanBeforeCreateTokens = false)
823
824
825
826
827
828
829
    {
        $prefixToken = bin2hex(openssl_random_pseudo_bytes(12));
        $getSuffixToken = bin2hex(openssl_random_pseudo_bytes(12));
        $postSuffixToken = bin2hex(openssl_random_pseudo_bytes(12));
        $formSuffixToken = bin2hex(openssl_random_pseudo_bytes(12));

        $dataToken = $this->request->session()->read('CreateUserAntiSpam');
830
        if (is_null($dataToken) | $cleanBeforeCreateTokens === true) {
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
            $dataToken = [];
        }
        $dataToken["$prefixToken"] = [
            "date"     => time(),
            "getToken" => "$prefixToken-$getSuffixToken",
            "postToken" => "$prefixToken-$postSuffixToken",
            "formToken" => "$prefixToken-$formSuffixToken",
        ];
        $this->request->session()->write('CreateUserAntiSpam', $dataToken);
        return "$prefixToken-$getSuffixToken";
    }

    /**
     * Tooling for "add" method: get current anti-spam token based on current HTTP method
     * @return string
     */
    private function addUserGetCurrentToken()
    {
        $method = strtolower($this->request->method());
        if ($method === 'get') {
            return strip_tags($this->request->query('t1'));
        } elseif ($method === 'post') {
            return strip_tags($this->request->query('t2'));
        }
        return ''; // wrong HTTP method
    }

    /**
     * Tooling for "add" method: check if current anti-spam token in URL is valid
     * @return bool
     */
    private function addUserIsValidTokenInUrl()
    {
        $token = $this->addUserGetCurrentToken();
        if (empty($token)) {
            return false; // wrong HTTP method or token parameter in the URL does not exist
        } else {
            $method = strtolower($this->request->method());
            $prefixToken = $this->addUserGetPrefixToken($token);
            $availableTokens = $this->request->session()->read('CreateUserAntiSpam');
            if (!isset($availableTokens[$prefixToken])) {
                return false;
            } elseif ($availableTokens[$prefixToken][$method .'Token'] !== $token) {
                return false;
            }
        }
        return true;
    }

    /**
     * Tooling for "add" method: get anti-spam prefix token
     *
     * @param string $token
     * @return mixed|string
     */
    private function addUserGetPrefixToken($token)
    {
        $tokenData = explode('-', $token);
        return $tokenData[0];
    }

    /**
     * Tooling for "add" method: get current token by type ('get', 'post' or 'form')
     *
     * @param string $type  'get', 'post' or 'form'
     * @return string
     */
    private function addUserGetTokenByType(string $type)
    {
        $prefixToken = $this->addUserGetPrefixToken($this->addUserGetCurrentToken());
        $availableTokens = $this->request->session()->read('CreateUserAntiSpam');
        $token = '';
        if (isset($availableTokens["$prefixToken"][$type.'Token'])) {
            $token = $availableTokens["$prefixToken"][$type.'Token'];
        }
        return $token;
    }

Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
909
    /**
910
911
912
913
914
915
916
917
918
919
     * Tooling for "add" method: check if form is sent too quicky
     * @return bool
     */
    private function addUserIsFormSentTooQuickly()
    {
        $prefixToken = $this->addUserGetPrefixToken($this->addUserGetCurrentToken());
        $availableTokens = $this->request->session()->read('CreateUserAntiSpam');
        if (isset($availableTokens["$prefixToken"])) {
            $tokenTimestamp = $availableTokens["$prefixToken"]['date'];
            $diffTimestamp = time() - $tokenTimestamp;
920
            if ($diffTimestamp >= Configure::read('MIN_TIME_TO_SEND_SIGNUP_FORM')) {
921
922
923
924
925
926
927
928
                return false;
            }
        }
        return true;
    }


   /**
Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
929
930
931
932
933
934
     * Add method
     *
     * @return void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
935
936
        $message = "";
        $lang = $this->selectedLanguage;
937
938
939
940
941
942

        // If user is already logged in, redirects them to their profile page
        if (!is_null($this->Auth->user('id'))) {
            return $this->redirect("/$lang/users/". $this->Auth->user('id'));
        }

943
944
945
946
947
        if (!empty($this->request->data)) {
            $user = $this->Users->newEntity($this->request->data);
        } else {
            $user = $this->Users->newEntity();
        }
948

949
        // Force token-based URL (HTTP GET and POST methods), expect for json API
950
951
952
953
954
955
        if (!$this->request->is('json')) {
            if ($this->request->method() === 'GET' && count($this->request->query) === 0) { // default page: /users/add
                return $this->redirect("/$lang/users/add?t1=". $this->addUserCreateTokens(false));
            } elseif ($this->addUserIsValidTokenInUrl() === false) {
                return $this->redirect("/$lang/users/add?t1=". $this->addUserCreateTokens(true));
            }
956
957
        }

Fabrice Gangler's avatar
Fabrice Gangler committed
958
        // Process form data
959
        if ($this->request->is('post')) {
960
961
962
963
964
            // Check that it's not a robot (expected token and speed submit), expect for json API
            if (!$this->request->is('json')) {
                $expectedFormToken = $this->addUserGetTokenByType('form');
                $formToken = $this->request->data("formToken");
                if ($expectedFormToken !== $formToken | $this->addUserIsFormSentTooQuickly()) {
965
                    return $this->redirect("/$lang/users/add?t1=". $this->addUserCreateTokens(true));
966
967
968
                }
            }

969
970
            // do not allow to upload an avatar when creating an account
            $this->request->data['photo'] = null;
971

972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
           // the "role" field needs a different treatment in production
           // to avoid that a user can be added with an "admin" role
           // via the form or the json API.
            if (Configure::read('debug') !== true) {
                // in production:
                // the role of a new user must always
                // be "User" (via the form or the json API)
                $this->request->data['role'] = 'User';
            } else {
                // If debug mode is enabled,
                // we must allow the addition of a user via the form
                // by adding the missing field "role" with the value "user".
                if (isset($this->request->data['submit_signUpForm'])) {
                    $this->request->data['role'] = 'User';
                }
                // The "else" part of this "if"
                // concerns the JSON interrogation (used only by unit test), and thus is not relevant
            }

Pastor Mickaël's avatar
CRUD  
Pastor Mickaël committed
991
            $user = $this->Users->patchEntity($user, $this->request->data);
992

993
            if ($this->Users->save($user)) {
994
995
                $message = "Success";
                $this->Flash->success(__d("Forms", "Your are registred on the Comptoir du Libre, welcome !"));
996
                $this->request->session()->write('CreateUserAntiSpam', []); // Unset tokens
997
998
999
1000
                if (!$this->request->is('json')) {
                    $currentUser = $this->Auth->identify();
                    $currentUser["user_type"] = $this->Users
                        ->UserTypes
For faster browsing, not all history is shown. View entire blame