TaxonomysSoftwaresController.php 10 KB
Newer Older
1
2
3
<?php
namespace App\Controller\Api\V1;

4
use App\Controller\Api\V1\Taxonomy\CommonTaxonomySoftwareController;
5
6
use App\Model\Entity\Software;
use App\Model\Entity\User;
7
use App\Model\Table\TaxonomysSoftwaresTable;
8
9
10
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Network\Exception\NotFoundException;
use Cake\Network\Response;
11
use Cake\ORM\TableRegistry;
12
13
14

/**
 * TaxonomysSoftwares Controller
15
16
17
18
19
20
21
22
23
 * - define actions allowed to editor
 * - define actions allowed to connected user
 * - define actions allowed to anonymous user
 * - implemente actions used by editor, connected user and anonymous user
 *
 * notice:
 * - actions dedicated to admin must be implemented in the parent class.
 * - beforeFilter() is defined in the parent class and should not be overwritten.
 * - isAuthorized() is defined in the parent class and should not be overwritten.
24
25
26
 *
 * @property TaxonomysSoftwaresTable $TaxonomysSoftwares
 */
27
class TaxonomysSoftwaresController extends CommonTaxonomySoftwareController
28
29
30
{

    /**
31
32
     * Actions allowed only to editor (connected user + business rules)
     * @var array
33
     */
34
    protected $actionsAllowedOnlyToEditor = [
35
        'mappingForm',
36
    ];
37
38

    /**
39
40
     * Actions allowed only for connected user
     * @var array
41
     */
42
    protected $actionsAllowedOnlyToConnectedUser = [];
43
44

    /**
45
46
     * Actions allowed to everyone
     * @var array
47
     */
48
    protected $actionsAllowedToEveryone = [];
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65


    /**
     * Mapping form used by connected user (type = "Administration")
     * after registering as user of a sofware.
     *
     *   URL: /fr/mappingForm/<softwareId>
     *        /en/mappingForm/<softwareId>
     *        /api/v1/taxonomys-softwares/mappingForm                   ---> redirect to '/en/mapping/'
     *        /api/v1/taxonomys-softwares/mappingForm/<softwareId>      ---> redirect to '/en/mappingForm/<softwareId>'
     *        /api/v1/taxonomys-softwares/mappingForm.json              ---> disable via parent::beforeFilter()
     *        /api/v1/taxonomys-softwares/mappingForm/<softwareId>.json ---> disable via parent::beforeFilter()
     *
     * @return Response|null
     */
    public function mappingForm($softwareId = null)
    {
66
        // Get taxonomy data
67
68
        $mappingTaxons = $this->getMappingTaxons($this->selectedLanguage);
        $mappingHead = $this->getmappingFirstLevels($this->selectedLanguage);
69

70
71
72
73
        // Get user
        $user = TableRegistry::get("Users")->get($this->Auth->user('id'));
        $userId = (int) $user->id;

74
75
76
77
78
        // $softwareId is not null only with /api/v1/ prefix
        if (is_null($softwareId)) { // Get the ID from the URL
            if (isset($this->request->params['softwareId'])) {
                $softwareId = $this->request->params['softwareId'];
            } else {
79
                return $this->redirect($this->getBaseUrl('mapping'), 301);
80
81
82
83
84
85
86
87
88
            }
        }

        // Get software
        $softwaresTable = TableRegistry::get("Softwares");
        $softwareId = (int) $softwareId;
        try {
            $software = $softwaresTable->get($softwareId);
        } catch (RecordNotFoundException $e) { // When there is no $softwareId record in database
89
            return $this->redirect($this->getBaseUrl('mapping'), 301);
90
91
92
93
94
        }

        // Check that the current URL is correct
        $lang = $this->selectedLanguage;
        $allowedUrl = "/$lang/mappingForm/$softwareId";
95
        if ($allowedUrl !== $this->request->here(false)) {
96
97
98
            return $this->redirect("$allowedUrl", 301);
        }

99
100
101
102
103
104
105
106
107
108
109
        // Check if current user is already a "user of"
        $registry = TableRegistry::get("RelationshipsSoftwaresUsers");
        $userOf = $registry->exists([
            'user_id' => $userId,
            'software_id' => $softwareId,
            'relationship_id' =>  $this->getRelationshipIdByName('UserOf'),
        ]);
        if ($userOf === false) { // not already "user of"
            return $this->redirect("/$lang/softwares/$softwareId", 302);
        }

110
        // Get already existing associations between the user, the software and the taxonomies
111
        $existingEntries = $this->TaxonomysSoftwares->getListByUserIdBySofwareId($userId, $softwareId);
112
113
114
115
116
117
118
119
120
121
122
                // example: Array( <taxonId> => taxonomySoftware, ...)

        // Form processing
        if (isset($this->request->data['id'])) { // form sent
            $processing = $this->processingMappingForm($software, $user, $existingEntries);
            if ($processing === true) {
                return $this->redirect("/$lang/softwares/" . $software->get('id'));
            } else {
                return $this->redirect("/$lang/mappingForm/" . $software->get('id'));
            }
        }
123
124

        // Parameters for the view
125
        $this->set(compact('user'));
126
        $this->set(compact('software'));
127
128
129
130
        $this->set(compact('existingEntries'));
        $this->set(compact('mappingTaxons'));
        $this->set(compact('mappingHead'));
        $this->set('_serialize', ['existingEntries']);
131
        $this->set('_serialize', ['software']);
132
133
        $this->set('_serialize', ['mappingTaxons']);
        $this->set('_serialize', ['mappingHead']);
134
135
136
137
138
139
140
141
142
143
144
145
146

        // Breadcrumbs
        $links = array();
        $links[] = [
            'name' => __d('Breadcrumbs', 'Software.ListOfSoftware'),
            'url' => 'softwares'
        ];
        $links[] = [
            'name' => $software->softwarename,
            'url' => "softwares/". $software->id
        ];
        $links[] = [
        //    'name' => __d('Breadcrumbs', __d("Taxonomy", "TaxonomySoftware.Form.Add.Breadcrumbs")),
Fabrice Gangler's avatar
Fabrice Gangler committed
147
            'name' => __d('Breadcrumbs', __d("Softwares", "Softwares.Users.DeclareAs.user.addMessage")),
148
149
150
151
            'url' => "mappingForm/". $software->id
        ];
        $this->setBreadcrumbs($links);
    }
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258


    /**
     * Processing mapping form
     *
     * Two cases:
     * - Add/Edit form sent empty ---> sub-processing by $this->processingMappingEmptyForm()
     * - Add/Edit form sent with data --> sub-processing by $this->processingMappingFormWithData()
     *
     * @param Software $software
     * @param User $user
     * @param array $existingEntries   example: [ <taxonId> => taxonomySoftware, ...]
     * @return bool
     */
    final private function processingMappingForm(Software $software, User $user, array $existingEntries): bool
    {
        $processing = true;

        // Form sent empty
        if (!isset($this->request->data['taxonCheckboxes']) || count($this->request->data['taxonCheckboxes']) === 0) {
            $processing = $this->processingMappingEmptyForm($existingEntries); // calls flash messages directly
        } else { // Form sent with data
            $processing = $this->processingMappingFormWithData($software, $user, $existingEntries);
            if ($processing === true) {
                $this->Flash->success(__d("Taxonomy", "TaxonomySoftware.FormProcessing.sucessMsg"));
            } else {
                $this->Flash->error(__d("Taxonomy", "TaxonomySoftware.FormProcessing.errorMsg"));
            }
        }
        return $processing;
    }


    /**
     * Processing add/edit form sent with data
     *
     * @param Software $software
     * @param User $user
     * @param array $existingEntries   example: [ <taxonId> => taxonomySoftware, ...]
     * @return bool
     */
    final private function processingMappingFormWithData(Software $software, User $user, array $existingEntries): bool
    {
        $processing = true;
        $softwareId = $software->id;
        $userId = $user->id;
        $selectedTaxon = $this->request->data['taxonCheckboxes'];
        foreach ($selectedTaxon as $idTaxon) {
            $idTaxon = (int) $idTaxon;
            // Preparing to delete old entries that have not been selected
            if (isset($existingEntries[$idTaxon])) {
                unset($existingEntries[$idTaxon]);
            } else {
                // Add new entries
                $taxonomySoftware = $this->TaxonomysSoftwares->newEntity();
                $taxonomySoftware->set('taxonomy_id', $idTaxon);
                $taxonomySoftware->set('software_id', $softwareId);
                $taxonomySoftware->set('user_id', $userId);
                // Additional form ----> to be reviewed (refs. z881)
                /////////////////////////////////////////////////////////
                //    if (isset($this->request->data['comment'])) {
                //        $comment = trim(strip_tags($this->request->data['comment']));
                //        if (!empty($comment)) {
                //            $taxonomySoftware->set('comment', "$comment");
                //        }
                //    }
                if (false === $this->TaxonomysSoftwares->save($taxonomySoftware)) {
                    $processing = false;
                }
            }
        }
        // Delete old entries that have not been selected.
        if (false === $this->TaxonomysSoftwares->deleteRecords($existingEntries)) {
            $processing = false;
        }
        return $processing;
    }

    /**
     * Processing empty mapping form
     *
     * Two cases:
     * - Add form sent empty
     * - Edit form sent empty --> delete all database entries
     *
     * @param array $existingEntries   example: [ taxonomySoftware, ...]
     * @return bool
     */
    final private function processingMappingEmptyForm(array $existingEntries): bool
    {
        $processing = true;
        if (count($existingEntries) === 0) { // Add form sent empty
            $this->Flash->error(__d("Taxonomy", "TaxonomySoftware.FormProcessing.formEmptyErrorMsg"));
            $processing = false;
        } else { // Edit form sent empty --> delete all database entries
            if (false === $this->TaxonomysSoftwares->deleteRecords($existingEntries)) {
                $processing = false;
            }

            if ($processing === true) {
                $this->Flash->success(__d("Taxonomy", "TaxonomySoftware.FormProcessing.formEmptySucessMsg"));
            } else {
                $this->Flash->error(__d("Taxonomy", "TaxonomySoftware.FormProcessing.errorMsg"));
            }
        }
        return $processing;
    }
259
}