]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Controllers/Crud/DynamicFieldsController.php
367d3138e0291e949e17d0ca690c1ec92bdadadd
[galette.git] / galette / lib / Galette / Controllers / Crud / DynamicFieldsController.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Galette dynamic fields controller
7 *
8 * PHP version 5
9 *
10 * Copyright © 2020-2023 The Galette Team
11 *
12 * This file is part of Galette (http://galette.tuxfamily.org).
13 *
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
26 *
27 * @category Controllers
28 * @package Galette
29 *
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2020-2023 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.9.4dev - 2020-05-02
35 */
36
37 namespace Galette\Controllers\Crud;
38
39 use Galette\IO\File;
40 use Galette\Repository\DynamicFieldsSet;
41 use Throwable;
42 use Galette\Controllers\CrudController;
43 use Slim\Psr7\Request;
44 use Slim\Psr7\Response;
45 use Galette\DynamicFields\DynamicField;
46 use Analog\Analog;
47
48 /**
49 * Galette dynamic fields controller
50 *
51 * @category Controllers
52 * @name DynamicFieldsController
53 * @package Galette
54 * @author Johan Cwiklinski <johan@x-tnd.be>
55 * @copyright 2020-2023 The Galette Team
56 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
57 * @link http://galette.tuxfamily.org
58 * @since Available since 0.9.4dev - 2020-05-02
59 */
60
61 class DynamicFieldsController extends CrudController
62 {
63 // CRUD - Create
64
65 /**
66 * Add page
67 *
68 * @param Request $request PSR Request
69 * @param Response $response PSR Response
70 * @param string $form_name Form name
71 *
72 * @return Response
73 */
74 public function add(Request $request, Response $response, string $form_name = null): Response
75 {
76 $params = [
77 'page_title' => _T("Add field"),
78 'form_name' => $form_name,
79 'action' => 'add',
80 'perm_names' => DynamicField::getPermsNames(),
81 'mode' => (($request->getHeaderLine('X-Requested-With') === 'XMLHttpRequest') ? 'ajax' : ''),
82 'field_type_names' => DynamicField::getFieldsTypesNames()
83 ];
84
85 if ($this->session->dynamicfieldtype) {
86 $params['df'] = $this->session->dynamicfieldtype;
87 $this->session->dynamicfieldtype = null;
88 }
89
90 // display page
91 $this->view->render(
92 $response,
93 'pages/configuration_dynamic_field_form.html.twig',
94 $params
95 );
96 return $response;
97 }
98
99 /**
100 * Add action
101 *
102 * @param Request $request PSR Request
103 * @param Response $response PSR Response
104 * @param string $form_name Form name
105 *
106 * @return Response
107 */
108 public function doAdd(Request $request, Response $response, string $form_name = null): Response
109 {
110 $post = $request->getParsedBody();
111 $post['form_name'] = $form_name;
112
113 $error_detected = [];
114 $warning_detected = [];
115
116 if (isset($post['cancel'])) {
117 return $response
118 ->withStatus(301)
119 ->withHeader('Location', $this->cancelUri($this->getArgs($request)));
120 }
121
122 $df = DynamicField::getFieldType($this->zdb, $post['field_type']);
123
124 try {
125 $df->store($post);
126 $error_detected = $df->getErrors();
127 $warning_detected = $df->getWarnings();
128 } catch (Throwable $e) {
129 $msg = 'An error occurred adding new dynamic field.';
130 Analog::log(
131 $msg . ' | ' .
132 $e->getMessage(),
133 Analog::ERROR
134 );
135 if (GALETTE_MODE == 'DEV') {
136 throw $e;
137 }
138 $error_detected[] = _T('An error occurred adding dynamic field :(');
139 }
140
141 //flash messages
142 if (count($error_detected) > 0) {
143 foreach ($error_detected as $error) {
144 $this->flash->addMessage(
145 'error_detected',
146 $error
147 );
148 }
149 } else {
150 $this->flash->addMessage(
151 'success_detected',
152 _T('Dynamic field has been successfully stored!')
153 );
154 }
155
156 if (count($warning_detected) > 0) {
157 foreach ($warning_detected as $warning) {
158 $this->flash->addMessage(
159 'warning_detected',
160 $warning
161 );
162 }
163 }
164
165 //handle redirections
166 if (count($error_detected) > 0) {
167 //something went wrong :'(
168 $this->session->dynamicfieldtype = $df;
169 return $response
170 ->withStatus(301)
171 ->withHeader(
172 'Location',
173 $this->routeparser->urlFor(
174 'addDynamicField',
175 ['form_name' => $form_name]
176 )
177 );
178 } else {
179 if (!$df instanceof \Galette\DynamicFields\Separator) {
180 return $response
181 ->withStatus(301)
182 ->withHeader(
183 'Location',
184 $this->routeparser->urlFor(
185 'editDynamicField',
186 [
187 'form_name' => $form_name,
188 'id' => $df->getId()
189 ]
190 )
191 );
192 }
193
194 return $response
195 ->withStatus(301)
196 ->withHeader(
197 'Location',
198 $this->routeparser->urlFor(
199 'configureDynamicFields',
200 ['form_name' => $form_name]
201 )
202 );
203 }
204 }
205
206 // /CRUD - Create
207 // CRUD - Read
208
209 /**
210 * List page
211 *
212 * @param Request $request PSR Request
213 * @param Response $response PSR Response
214 * @param string $option One of 'page' or 'order'
215 * @param string|integer $value Value of the option
216 * @param string $form_name Form name
217 *
218 * @return Response
219 */
220 public function list(
221 Request $request,
222 Response $response,
223 $option = null,
224 $value = null,
225 $form_name = 'adh'
226 ): Response {
227 if (isset($_POST['form_name']) && trim($_POST['form_name']) != '') {
228 $form_name = $_POST['form_name'];
229 }
230 $fields = new DynamicFieldsSet($this->zdb, $this->login);
231 $fields_list = $fields->getList($form_name);
232
233 $params = [
234 'fields_list' => $fields_list,
235 'form_name' => $form_name,
236 'form_title' => DynamicField::getFormTitle($form_name),
237 'page_title' => _T("Dynamic fields configuration")
238 ];
239
240 $tpl = 'pages/configuration_dynamic_fields.html.twig';
241 //Render directly template if we called from ajax,
242 //render in a full page otherwise
243 if (
244 ($request->getHeaderLine('X-Requested-With') === 'XMLHttpRequest')
245 || isset($request->getQueryParams()['ajax'])
246 && $request->getQueryParams()['ajax'] == 'true'
247 ) {
248 $tpl = 'elements/edit_dynamic_fields.html.twig';
249 } else {
250 $all_forms = DynamicField::getFormsNames();
251 $params['all_forms'] = $all_forms;
252 }
253
254 // display page
255 $this->view->render(
256 $response,
257 $tpl,
258 $params
259 );
260 return $response;
261 }
262
263 /**
264 * Filtering
265 *
266 * @param Request $request PSR Request
267 * @param Response $response PSR Response
268 *
269 * @return Response
270 */
271 public function filter(Request $request, Response $response): Response
272 {
273 //no filtering
274 return $response;
275 }
276
277 /**
278 * Get a dynamic file
279 *
280 * @param Request $request PSR Request
281 * @param Response $response PSR Response
282 * @param string $form_name Form name
283 * @param integer $id Object ID
284 * @param integer $fid Dynamic fields ID
285 * @param integer $pos Dynamic field position
286 * @param string $name File name
287 *
288 * @return Response
289 */
290 public function getDynamicFile(
291 Request $request,
292 Response $response,
293 string $form_name,
294 int $id,
295 int $fid,
296 int $pos,
297 string $name
298 ): Response {
299 $object_class = DynamicFieldsSet::getClasses()[$form_name];
300 if ($object_class === 'Galette\Entity\Adherent') {
301 $object = new $object_class($this->zdb);
302 } else {
303 $object = new $object_class($this->zdb, $this->login);
304 }
305
306 $object
307 ->disableAllDeps()
308 ->enableDep('dynamics')
309 ->load($id);
310 $fields = $object->getDynamicFields()->getFields();
311 $field = $fields[$fid] ?? null;
312
313 $denied = null;
314 if (!$object->canShow($this->login)) {
315 if (!isset($fields[$fid])) {
316 //field does not exist or access is forbidden
317 $denied = true;
318 } else {
319 $denied = false;
320 }
321 }
322
323 if ($denied === true) {
324 $this->flash->addMessage(
325 'error_detected',
326 _T("You do not have permission for requested URL.")
327 );
328
329 $route_name = 'member';
330 if ($form_name == 'contrib') {
331 $route_name = 'contribution';
332 } elseif ($route_name == 'trans') {
333 $route_name = 'transaction';
334 }
335 return $response
336 ->withHeader(
337 'Location',
338 $this->routeparser->urlFor(
339 $route_name,
340 ['id' => $id]
341 )
342 );
343 }
344
345 $filename = $field->getFileName($id, $pos);
346
347 if ($form_name !== 'member' && !file_exists(GALETTE_FILES_PATH . $filename)) {
348 //handle old names for non adh dynamic files
349 $test_filename = $field->getFileName($id, $pos, 'member');
350 if (file_exists(GALETTE_FILES_PATH . $test_filename)) {
351 //rename old file to new name
352 rename(GALETTE_FILES_PATH . $test_filename, GALETTE_FILES_PATH . $filename);
353 }
354 }
355
356 if (file_exists(GALETTE_FILES_PATH . $filename)) {
357 $type = File::getMimeType(GALETTE_FILES_PATH . $filename);
358
359 $response = $response->withHeader('Content-Description', 'File Transfer')
360 ->withHeader('Content-Type', $type)
361 ->withHeader('Content-Disposition', 'attachment;filename="' . $name . '"')
362 ->withHeader('Pragma', 'no-cache')
363 ->withHeader('Content-Transfer-Encoding', 'binary')
364 ->withHeader('Expires', '0')
365 ->withHeader('Cache-Control', 'must-revalidate')
366 ->withHeader('Pragma', 'public');
367
368 $stream = fopen('php://memory', 'r+');
369 fwrite($stream, file_get_contents(GALETTE_FILES_PATH . $filename));
370 rewind($stream);
371
372 return $response->withBody(new \Slim\Psr7\Stream($stream));
373 } else {
374 Analog::log(
375 'A request has been made to get a dynamic file named `' .
376 $filename . '` that does not exists.',
377 Analog::WARNING
378 );
379
380 $this->flash->addMessage(
381 'error_detected',
382 _T("The file does not exists or cannot be read :(")
383 );
384
385 return $response
386 ->withHeader(
387 'Location',
388 $this->routeparser->urlFor('member', ['id' => $id])
389 );
390 }
391 }
392
393 // /CRUD - Read
394 // CRUD - Update
395
396 /**
397 * Edit page
398 *
399 * @param Request $request PSR Request
400 * @param Response $response PSR Response
401 * @param integer $id Dynamic field id
402 * @param string $form_name Form name
403 *
404 * @return Response
405 */
406 public function edit(Request $request, Response $response, int $id, $form_name = null): Response
407 {
408 $df = null;
409 if ($this->session->dynamicfieldtype) {
410 $df = $this->session->dynamicfieldtype;
411 $this->session->dynamicfieldtype = null;
412 } else {
413 $df = DynamicField::loadFieldType($this->zdb, $id);
414 if ($df === false) {
415 $this->flash->addMessage(
416 'error_detected',
417 _T("Unable to retrieve field information.")
418 );
419 return $response
420 ->withStatus(301)
421 ->withHeader('Location', $this->routeparser->urlFor('configureDynamicFields'));
422 }
423 }
424
425 $params = [
426 'page_title' => _T("Edit field"),
427 'action' => 'edit',
428 'form_name' => $form_name,
429 'perm_names' => DynamicField::getPermsNames(),
430 'mode' => (($request->getHeaderLine('X-Requested-With') === 'XMLHttpRequest') ? 'ajax' : ''),
431 'df' => $df
432 ];
433
434 // display page
435 $this->view->render(
436 $response,
437 'pages/configuration_dynamic_field_form.html.twig',
438 $params
439 );
440 return $response;
441 }
442
443 /**
444 * Edit action
445 *
446 * @param Request $request PSR Request
447 * @param Response $response PSR Response
448 * @param integer $id Dynamic field id
449 * @param string $form_name Form name
450 *
451 * @return Response
452 */
453 public function doEdit(Request $request, Response $response, int $id = null, string $form_name = null): Response
454 {
455 $post = $request->getParsedBody();
456 $post['form_name'] = $form_name;
457
458 if (isset($post['cancel'])) {
459 return $response
460 ->withStatus(301)
461 ->withHeader('Location', $this->cancelUri($this->getArgs($request)));
462 }
463
464 $error_detected = [];
465 $warning_detected = [];
466
467 $field_id = $id;
468 $df = DynamicField::loadFieldType($this->zdb, $field_id);
469
470 try {
471 $df->store($post);
472 $error_detected = $df->getErrors();
473 $warning_detected = $df->getWarnings();
474 } catch (Throwable $e) {
475 $msg = 'An error occurred storing dynamic field ' . $df->getId() . '.';
476 Analog::log(
477 $msg . ' | ' .
478 $e->getMessage(),
479 Analog::ERROR
480 );
481 if (GALETTE_MODE == 'DEV') {
482 throw $e;
483 }
484 $error_detected[] = _T('An error occurred editing dynamic field :(');
485 }
486
487 //flash messages
488 if (count($error_detected) > 0) {
489 foreach ($error_detected as $error) {
490 $this->flash->addMessage(
491 'error_detected',
492 $error
493 );
494 }
495 } else {
496 $this->flash->addMessage(
497 'success_detected',
498 _T('Dynamic field has been successfully stored!')
499 );
500 }
501
502 if (count($warning_detected) > 0) {
503 foreach ($warning_detected as $warning) {
504 $this->flash->addMessage(
505 'warning_detected',
506 $warning
507 );
508 }
509 }
510
511 //handle redirections
512 if (count($error_detected) > 0) {
513 //something went wrong :'(
514 $this->session->dynamicfieldtype = $df;
515 return $response
516 ->withStatus(301)
517 ->withHeader(
518 'Location',
519 $this->routeparser->urlFor(
520 'editDynamicField',
521 [
522 'form_name' => $form_name,
523 'id' => $id
524 ]
525 )
526 );
527 } else {
528 return $response
529 ->withStatus(301)
530 ->withHeader(
531 'Location',
532 $this->routeparser->urlFor(
533 'configureDynamicFields',
534 ['form_name' => $form_name]
535 )
536 );
537 }
538 }
539
540 // /CRUD - Update
541 // CRUD - Delete
542
543 /**
544 * Get redirection URI
545 *
546 * @param array $args Route arguments
547 *
548 * @return string
549 */
550 public function redirectUri(array $args)
551 {
552 return $this->routeparser->urlFor('configureDynamicFields', ['form_name' => $args['form_name']]);
553 }
554
555 /**
556 * Get form URI
557 *
558 * @param array $args Route arguments
559 *
560 * @return string
561 */
562 public function formUri(array $args)
563 {
564 return $this->routeparser->urlFor(
565 'doRemoveDynamicField',
566 ['id' => $args['id'], 'form_name' => $args['form_name']]
567 );
568 }
569
570 /**
571 * Get confirmation removal page title
572 *
573 * @param array $args Route arguments
574 *
575 * @return string
576 */
577 public function confirmRemoveTitle(array $args)
578 {
579 $field = DynamicField::loadFieldType($this->zdb, (int)$args['id']);
580 if ($field === false) {
581 $this->flash->addMessage(
582 'error_detected',
583 _T("Requested field does not exists!")
584 );
585 return _T("Requested field does not exists!");
586 }
587
588 return sprintf(
589 _T('Remove dynamic field %1$s'),
590 $field->getName()
591 );
592 }
593
594 /**
595 * Remove object
596 *
597 * @param array $args Route arguments
598 * @param array $post POST values
599 *
600 * @return boolean
601 */
602 protected function doDelete(array $args, array $post)
603 {
604 $field_id = (int)$post['id'];
605 $field = DynamicField::loadFieldType($this->zdb, $field_id);
606 return $field->remove();
607 }
608
609 // /CRUD - Delete
610 // /CRUD
611
612 /**
613 * Move field
614 *
615 * @param Request $request PSR Request
616 * @param Response $response PSR Response
617 * @param integer $id Field id
618 * @param string $form_name Form name
619 * @param string $direction One of DynamicField::MOVE_*
620 *
621 * @return Response
622 */
623 public function move(
624 Request $request,
625 Response $response,
626 int $id,
627 string $form_name,
628 string $direction
629 ): Response {
630 $field = DynamicField::loadFieldType($this->zdb, $id);
631 if ($field->move($direction)) {
632 $this->flash->addMessage(
633 'success_detected',
634 _T("Field has been successfully moved")
635 );
636 } else {
637 $this->flash->addMessage(
638 'error_detected',
639 _T("An error occurred moving field :(")
640 );
641 }
642
643 return $response
644 ->withStatus(301)
645 ->withHeader('Location', $this->routeparser->urlFor('configureDynamicFields', ['form_name' => $form_name]));
646 }
647 }