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