aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/studip_controller.php
blob: 7444dba4ce13e1ec28cfe09d1dfb1fc6dde7e89b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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
761
762
763
764
765
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
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
<?php
/*
 * studip_controller.php - studip controller base class
 * Copyright (c) 2009  Elmar Ludwig
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 */

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

require_once 'studip_controller_properties_trait.php';
require_once 'studip_response.php';

/**
 * @property StudipResponse $response
 */
abstract class StudipController extends Trails_Controller
{
    use StudipControllerPropertiesTrait;

    protected $with_session = false; //do we need to have a session for this controller
    protected $allow_nobody = true; //should 'nobody' allowed for this controller or redirected to login?
    protected $_autobind = false;

    /**
     * @return false|void
     */
    public function before_filter(&$action, &$args)
    {
        $this->current_action = $action;
        // allow only "word" characters in arguments
        $this->validate_args($args);

        parent::before_filter($action, $args);

        if ($this->with_session) {
            # open session
            page_open([
                'sess' => 'Seminar_Session',
                'auth' => $this->allow_nobody ? 'Seminar_Default_Auth' : 'Seminar_Auth',
                'perm' => 'Seminar_Perm',
                'user' => 'Seminar_User'
            ]);

            // show login-screen, if authentication is "nobody"
            $GLOBALS['auth']->login_if((Request::get('again') || !$this->allow_nobody) && $GLOBALS['user']->id == 'nobody');

            // Setup flash instance
            $this->flash = Trails_Flash::instance();

            // set up user session
            include 'lib/seminar_open.php';
        }

        // Set generic attribute that indicates whether the request was sent
        // via ajax or not
        $this->via_ajax = Request::isXhr();

        # Set base layout
        #
        # If your controller needs another layout, overwrite your controller's
        # before filter:
        #
        #   class YourController extends AuthenticatedController {
        #     function before_filter(&$action, &$args) {
        #       parent::before_filter($action, $args);
        #       $this->set_layout("your_layout");
        #     }
        #   }
        #
        # or unset layout by sending:
        #
        #   $this->set_layout(NULL)
        #
        $layout_file = Request::isXhr()
                     ? 'layouts/dialog.php'
                     : 'layouts/base.php';
        $layout = $GLOBALS['template_factory']->open($layout_file);
        $this->set_layout($layout);

        $this->set_content_type('text/html;charset=utf-8');
    }

    /**
     * Extended method to inject extended response object.
     */
    public function erase_response()
    {
        parent::erase_response();

        $this->response = new StudipResponse();
    }

    /**
     * Hooked perform method in order to inject body element id creation.
     *
     * In order to avoid clashes, these body element id will be joined
     * with a minus sign. Otherwise the controller "x" with action
     * "y_z" would be given the same id as the controller "x/y" with
     * the action "z", namely "x_y_z". With the minus sign this will
     * result in the ids "x-y_z" and "x_y-z".
     *
     * Plugins will always have a leading 'plugin-' and the decamelized
     * plugin name in front of the id.
     *
     * @param String $unconsumed_path Path segment containing action and
     *                                optionally arguments or format
     * @return Trails_Response from parent controller
     */
    public function perform($unconsumed_path)
    {
        // Set body element id if it has not already been set
        if (!PageLayout::hasBodyElementId()) {
            $body_id = $this->getBodyElementIdForControllerAndAction($unconsumed_path);
            PageLayout::setBodyElementId($body_id);
        }

        return parent::perform($unconsumed_path);
    }

    /**
     * Callback function being called after an action is executed.
     *
     * @param string Name of the action to perform.
     * @param array  An array of arguments to the action.
     *
     * @return void
     */
    public function after_filter($action, $args)
    {
        parent::after_filter($action, $args);

        if (Request::isXhr() && !isset($this->response->headers['X-Title']) && PageLayout::hasTitle()) {
            $this->response->add_header('X-Title', rawurlencode(PageLayout::getTitle()));
        }
        if (Request::isXhr() && !isset($this->response->headers['X-WikiLink']) && PageLayout::getHelpKeyword()) {
            $this->response->add_header('X-WikiLink', format_help_url(PageLayout::getHelpKeyword()));
        }

        if ($this->with_session) {
            page_close();
        }
    }

    /**
     * Validate arguments based on a list of given types. The types are:
     * 'int', 'float', 'option' and 'string'. If the list of types is NULL
     * or shorter than the argument list, 'option' is assumed for all
     * remaining arguments. 'option' differs from Request::option() in
     * that it also accepts the charaters '-' and ',' in addition to all
     * word characters.
     *
     * Since Stud.IP 4.0 it is also possible to directly inject
     * SimpleORMap objects. If types is NULL, the signature of the called
     * action is analyzed and any type hint that matches a sorm class
     * will be used to create an object using the argument as the id
     * that is passed to the object's constructor.
     *
     * If $_autobind is set to true, the created object is also assigned
     * to the controller so that it is available in a view.
     *
     * @param array $args  an array of arguments to the action
     * @param array $types list of argument types (optional)
     */
    public function validate_args(&$args, $types = null)
    {
        $class_infos = [];

        if ($types === null) {
            $types = [];
        }

        if ($this->has_action($this->current_action)) {
            $reflection = new ReflectionMethod($this, $this->current_action . '_action');
            $parameters = $reflection->getParameters();
            foreach ($parameters as $i => $parameter) {
                $class_type = $parameter->getType();

                if (
                    !$class_type
                    || !class_exists($class_type->getName())
                    || !is_a($class_type->getName(), SimpleORMap::class, true)
                ) {
                    continue;
                }

                $types[$i] = 'sorm';
                $class_infos[$i] = [
                    'model'    => $class_type->getName(),
                    'var'      => $parameter->getName(),
                    'optional' => $parameter->isOptional(),
                ];

                if ($parameter->isOptional() && !isset($args[$i])) {
                    $args[$i] = $parameter->getDefaultValue();
                }
            }
        }

        foreach ($args as $i => &$arg) {
            $type = $types[$i] ?? 'option';
            switch ($type) {
                case 'int':
                    $arg = (int) $arg;
                    break;

                case 'float':
                    $arg = (float) strtr($arg, ',', '.');
                    break;

                case 'option':
                    if (preg_match('/[^\\w,-]/', $arg)) {
                        throw new Trails_Exception(400);
                    }
                    break;

                case 'sorm':
                    $info = $class_infos[$i];

                    $id = null;
                    if ($arg != -1) {
                        $id = $arg;
                    }
                    if (mb_strpos($id, SimpleORMap::ID_SEPARATOR) !== false) {
                        $id = explode(SimpleORMap::ID_SEPARATOR, $id);
                    }

                    $reflection = new ReflectionClass($info['model']);

                    $sorm = $reflection->newInstance($id);
                    if (!$info['optional'] && $sorm->isNew()) {
                        throw new Trails_Exception(
                            404,
                            "Parameter {$info['var']} could not be resolved with value {$arg}"
                        );
                    }

                    $arg = $sorm;
                    if ($this->_autobind) {
                        $this->{$info['var']} = $arg;
                    }
                    break;

                case 'string':
                    break;

                default:
                    throw new Trails_Exception(500, 'Unknown type "' . $type . '"');
            }
        }

        reset($args);
    }

    /**
     * Returns a URL to a specified route to your Trails application.
     * without first parameter the current action is used
     * if route begins with a / then the current controller ist prepended
     * if second parameter is an array it is passed to URLHeper
     *
     * @param  string   a string containing a controller and optionally an action
     * @param  string[] optional arguments
     *
     * @return string  a URL to this route
     */
    public function url_for($to = ''/* , ... */)
    {
        $args = func_get_args();

        // Try to create route if none given
        if ($to === '') {
            $args[0] = isset($this->parent_controller)
                     ? $this->parent_controller->current_action
                     : $this->current_action;
            return $this->action_url(...$args);
        }

        // Create url for a specific action
        // TODO: This seems odd. You kinda specify an absolute path
        //       to receive a relative url. Meh...
        //
        // @deprecated Do not use this, please!
        if ($to[0] === '/') {
            $args[0] = substr($to, 1);
            return $this->action_url(...$args);
        }

        // Check for absolute URL
        if ($this->isURL($to)) {
            throw new InvalidArgumentException(__METHOD__ . ' cannot be used with absolute URLs');
        }

        // Extract fragment (if any)
        if (strpos($to, '#') !== false) {
            list($args[0], $fragment) = explode('#', $to);
        }

        // Extract parameters (if any)
        $params = [];
        if (is_array(end($args))) {
            $params = array_pop($args);
        }

        // Map any sorm objects to their ids
        $args = array_map(function ($arg) {
            if (is_object($arg) && $arg instanceof SimpleORMap) {
                return $arg->isNew() ? -1 : $arg->id;
            }
            return $arg;
        }, $args);

        $url = parent::url_for(...$args);

        if (isset($fragment)) {
            $url .= '#' . $fragment;
        }
        return URLHelper::getURL($url, $params);
    }

    /**
     * Returns an escaped URL to a specified route to your Trails application.
     * without first parameter the current action is used
     * if route begins with a / then the current controller ist prepended
     * if second parameter is an array it is passed to URLHeper
     *
     * @param  string   a string containing a controller and optionally an action
     * @param  strings  optional arguments
     *
     * @return string  a URL to this route
     */
    public function link_for($to = ''/* , ... */)
    {
        return htmlReady($this->url_for(...func_get_args()));
    }

    /**
     * Redirects the user another page. Accepts multiple parameters just like
     * url_for().
     *
     * @param string $to
     * @see StudipController::url_for()
     */
    public function redirect($to)
    {
        $to = $this->adjustToArguments(...func_get_args());

        parent::redirect($to);
    }

    /**
     * Relocate the user to another location. This is a specialized version
     * of redirect that differs in two points:
     *
     * - relocate() will force the browser to leave the current dialog while
     *   redirect would refresh the dialog's contents
     * - relocate() accepts all the parameters that url_for() accepts so it's
     *   no longer neccessary to chain url_for() and redirect()
     *
     * @param String $to Location to redirect to
     */
    public function relocate($to)
    {
        $to = $this->adjustToArguments(...func_get_args());

        if (Request::isDialog()) {
            $this->response->add_header('X-Location', encodeURI($to));
            $this->render_nothing();
        } else {
            parent::redirect($to);
        }
    }

    /**
     * Returns a URL to a specified route to your Trails application, unless
     * the parameter is already a valid URL (which is returned unchanged).
     *
     * If no absolute url or more than one argument is given, url_for() is
     * used.
     */
    private function adjustToArguments(...$args): string
    {
        if (count($args) > 1 && $this->isURL($args[0])) {
            throw new InvalidArgumentException('Method may not be used with a URL and multiple parameters');
        }

        if (count($args) === 1 && $this->isURL($args[0])) {
            return $args[0];
        }

        return $this->url_for(...$args);
    }

    /**
     * Returns whether the given parameter is a valid url.
     *
     * @param string $to
     * @return bool
     */
    private function isURL(string $to): bool
    {
        return preg_match('#^(/|\w+://)#', $to);
    }

    /**
     * Exception handler called when the performance of an action raises an
     * exception.
     *
     * @param  object     the thrown exception
     */
    public function rescue($exception)
    {
        throw $exception;
    }

    /**
     * render given data as json, data is converted to utf-8
     *
     * @param mixed $data
     */
    public function render_json($data)
    {
        $json = json_encode($data);

        $this->set_content_type('application/json;charset=utf-8');
        $this->response->add_header('Content-Length', strlen($json));
        $this->render_text($json);
    }

    /**
     * Render given data as csv, data is assumed to be utf-8.
     * The first row of data may contain column titles.
     *
     * @param array $data       data as two dimensional array
     * @param string $filename  download file name (optional)
     * @param string $delimiter field delimiter char (optional)
     * @param string $enclosure field enclosure char (optional)
     */
    public function render_csv($data, $filename = null, $delimiter = ';', $enclosure = '"')
    {
        $this->set_content_type('text/csv; charset=UTF-8');

        $output = fopen('php://temp', 'rw');
        fputs($output, "\xEF\xBB\xBF");

        foreach ($data as $row) {
            fputcsv($output, $row, $delimiter, $enclosure);
        }

        rewind($output);
        $csv_data = stream_get_contents($output);
        fclose($output);

        if (isset($filename)) {
            $this->response->add_header('Content-Disposition', 'attachment; ' . encode_header_parameter('filename', $filename));
        }

        $this->response->add_header('Content-Length', strlen($csv_data));

        $this->render_text($csv_data);
    }

    /**
     * Renders a pdf file given by a TCPDF/ExportPDF object.
     *
     * @param TCPDF   $pdf      TCPDF object to render
     * @param string  $filename Filename
     * @param bool    $inline   Should the pdf be displayed inline (default: no)
     */
    protected function render_pdf(TCPDF $pdf, $filename, $inline = false)
    {
        $temp_file = $GLOBALS['TMP_PATH'] . '/' . md5(uniqid('pdf-file', true));
        $pdf->Output($temp_file, 'F');

        $disposition = $inline ? 'inline' : 'attachment';

        $this->render_temporary_file($temp_file, $filename, 'application/pdf', $disposition);
    }

    /**
     * Renders a file
     * @param string  $file                Path of the file to render
     * @param string  $filename            Name of the file displayed to user
     *                                     (will equal $file when missing)
     * @param string  $content_type        Optional content type (will be determined if missing)
     * @param string  $content_disposition Either attachment (default) or inline
     * @param Closure $callback            Optional callback when download has finished
     * @param int     $chunk_size          Optional size of chunks to send (default: 256k)
     */
    public function render_file(
        $file,
        $filename = null,
        $content_type = null,
        $content_disposition = 'attachment',
        Closure $callback = null,
        $chunk_size = 262144
    ) {
        if (!file_exists($file)) {
            throw new Trails_Exception(404);
        }

        if (!is_readable($file)) {
            throw new Trails_Exception(500);
        }

        if ($content_type === null) {
            $content_type = get_mime_type($filename ?: $file);
        }

        if (!in_array($content_type, get_mime_types())) {
            $content_type = 'application/octet-stream';
        }

        if ($content_type === 'application/octet-stream') {
            $content_disposition = 'attachment';
        }

        $this->set_content_type($content_type);
        $this->response->add_header(
            'Content-Disposition',
            "{$content_disposition}; " . encode_header_parameter(
                'filename',
                FileManager::cleanFileName($filename ?: basename($file))
            )
        );
        $this->response->add_header('Content-Length', filesize($file));
        $this->response->add_header('Content-Transfer-Encoding',  'binary');
        $this->response->add_header('Pragma', 'public');
        $this->render_text(function () use ($file, $chunk_size, $callback) {
            $fp = fopen($file, 'rb');

            while (!feof($fp)) {
                yield fgets($fp, $chunk_size);
            }

            fclose($fp);

            if ($callback) {
                $callback($file);
            }
        });
    }

    /**
     * Renders a temporary file which will be deleted after transmission.
     * This is just a convenience method so you don't have to write the delete
     * callback.
     *
     * @param string  $file                Path of the file to render
     * @param string  $filename            Name of the file displayed to user
     *                                     (will equal $file when missing)
     * @param string  $content_type        Optional content type (will be determined if missing)
     * @param string  $content_disposition Either attachment (default) or inline
     * @param Closure $callback            Optional callback when download has finished
     * @param int     $chunk_size          Optional size of chunks to send (default: 256k)
     */
    public function render_temporary_file(
        $file,
        $filename = null,
        $content_type = null,
        $content_disposition = 'attachment',
        Closure $callback = null,
        $chunk_size = 262144

    ) {
        $delete_callback = function ($file) use ($callback) {
            unlink($file);

            if ($callback) {
                $callback($file);
            }
        };

        $this->render_file(
            $file,
            $filename,
            $content_type,
            $content_disposition,
            $delete_callback,
            $chunk_size
        );
    }

    /**
     * relays current request to another controller and returns the response
     * the other controller is given all assigned properties, additional parameters are passed
     * through
     *
     * @param string $to_uri a trails route
     * @return Trails_Response
     */
    public function relay($to_uri/* , ... */)
    {
        $args = func_get_args();
        $uri = array_shift($args);
        [$controller_path, $unconsumed] = '' === $uri ? $this->dispatcher->default_route() : $this->dispatcher->parse($uri);

        $controller = $this->dispatcher->load_controller($controller_path);
        $assigns = $this->get_assigned_variables();
        unset($assigns['controller']);
        foreach ($assigns as $k => $v) {
            $controller->$k = $v;
        }
        $controller->layout = null;
        $controller->parent_controller = $this;
        array_unshift($args, $unconsumed);
        return $controller->perform_relayed(...$args);
    }

    /**
     * Relays current request and performs redirect if neccessary.
     *
     * @param string $to_uri a trails route
     * @return Trails_Response
     *
     * @see StudipController::relay()
     */
    public function relayWithRedirect(...$args): Trails_Response
    {
        $response = $this->relay(...$args);

        // If the relayed action should perform a redirect, do so
        if (isset($response->headers['Location'])) {
            header("Location: {$response->headers['Location']}");
            page_close();
            die;
        }

        return $response;
    }

    /**
     * perform a given action/parameter string from an relayed request
     * before_filter and after_filter methods are not called
     *
     * @see perform
     * @param string $unconsumed
     * @return Trails_Response
     */
    public function perform_relayed($unconsumed/* , ... */)
    {
        $args = func_get_args();
        $unconsumed = array_shift($args);

        [$action, $extracted_args, $format] = $this->extract_action_and_args($unconsumed);
        $this->format = isset($format) ? $format : 'html';
        $this->current_action = $action;
        $args = array_merge($extracted_args, $args);
        $callable = $this->map_action($action);

        if (is_callable($callable)) {
            $callable(...$args);
        } else {
            $this->does_not_understand($action, $args);
        }

        if (!$this->performed) {
            $this->render_action($action);
        }
        return $this->response;
    }

    /**
     * Renders a given template and returns the resulting string.
     *
     * @param string $template Name of the template file
     * @param mixed  $layout   Optional layout
     * @return string
     */
    public function render_template_as_string($template, $layout = null)
    {
        $template = $this->get_template_factory()->open($template);
        $template->set_layout($layout);
        $template->set_attributes($this->get_assigned_variables());
        return $template->render();
    }

    /**
     * Magic methods that intercepts all unknown method calls.
     * If a method is called that matches an action on this controller,
     * an url to that action is generated.
     *
     * Basically, this:
     *
     *    <code>$controller->url_for('foo/bar/baz/' . $param)</code>
     *
     * is equal to calling this on the Foo_BarController:
     *
     *    <code>$controller->baz($param)</code>
     *
     * @param String $method    Called method name
     * @param array  $argumetns Provided arguments
     * @return url to the requested action
     * @throws Trails_UnknownAction if no action matches the method
     */
    public function __call($method, $arguments)
    {
        $function = 'action_link';
        if (mb_strpos($method, 'Link') === mb_strlen($method) - 4) {
            $method = mb_substr($method, 0, -4);
        } elseif (mb_strpos($method, 'URL') === mb_strlen($method) - 3) {
            $function = 'action_url';
            $method = mb_substr($method, 0, -3);
        }

        if (!$this->has_action($method)) {
            throw new Trails_UnknownAction("Unknown action '{$method}'");
        }

        array_unshift($arguments, $method);
        return call_user_func_array([$this, $function], $arguments);
    }

    /**
     * Returns whether this controller has the specificed action.
     *
     * @param string $action Name of the action
     * @return true if action is defined, false otherwise
     */
    public function has_action($action)
    {
        return method_exists($this, $action . '_action')
            || ($this->parent_controller
                && $this->parent_controller->has_action($action));
    }

    /**
     * Generates the url for an action on this controller without the
     * neccessity to provide the full "path" to the action (since it
     * is implicitely known).
     *
     * Basically, this:
     *
     *    <code>$controller->url_for('foo/bar/baz/' . $param)</code>
     *
     * is equal to calling this on the Foo_BarController:
     *
     *    <code>$controller->action_url('baz/' . $param)</code>
     *
     * @param string $action Name of the action
     * @return string url to the requested action
     */
    public function action_url($action)
    {
        $arguments = func_get_args();
        $arguments[0] = $this->controller_path() . '/' . $arguments[0];

        return $this->url_for(...$arguments);
    }

    /**
     * Generates the link for an action on this controller without the
     * neccessity to provide the full "path" to the action (since it
     * is implicitely known).
     *
     * Basically, this:
     *
     *    <code>$controller->link_for('foo/bar/baz/' . $param)</code>
     *
     * is equal to calling this on the Foo_BarController:
     *
     *    <code>$controller->action_link('baz/' . $param)</code>
     *
     * @param string $action Name of the action
     * @return string to the requested action
     */
    public function action_link($action)
    {
        return htmlReady($this->action_url(...func_get_args()));
    }

    /**
     * Returns the url path to this controller.
     *
     * @return string url path to this controller
     */
    protected function controller_path()
    {
        $class = get_class($this->parent_controller ?? $this);
        $controller = mb_substr($class, 0, -mb_strlen('Controller'));
        $controller = strtosnakecase($controller);
        return preg_replace('/_{2,}/', '/', $controller);
    }


    /**
     * Validate the datetime according to specific format.
     *
     * @param string $datetime the datetime which should be validate
     * @param string $format the format that the datetime should have by default H:i for time
     *
     * @return bool result of validation
     */
    public function validate_datetime($datetime, $format = 'H:i')
    {
        $dt = DateTime::createFromFormat($format, $datetime);
        return $dt && $dt->format($format) == date('H:i',strtotime($datetime));
    }

    /**
     * Export xlsx and csv files via PhpSpreadsheet
     *
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function render_spreadsheet(
        array $header,
        array $data,
        string $format,
        string $filename,
        ?string $filepath = null
    ): void  {
        $render_to_browser = false;
        if ($filepath == null) {
            $render_to_browser = true;
            $filepath = tempnam($GLOBALS['TMP_PATH'], 'spreadsheet');
        }
        $spreadsheet = new Spreadsheet();
        $activeWorksheet = $spreadsheet->getActiveSheet();
        $activeWorksheet->fromArray($header);
        $activeWorksheet->fromArray($data, null, 'A2');

        if ($format === 'xlsx') {
            $writer = new Xlsx($spreadsheet);
        } elseif ($format === 'csv') {
            $writer = new Csv($spreadsheet);
        } else {
            throw new Exception("Format {$format} is not supported");
        }

        $writer->save($filepath);

        if ($render_to_browser) {
            $this->response->add_header('Cache-Control', 'cache, must-revalidate');
            $this->render_temporary_file(
                $filepath,
                $filename,
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            );
        }
    }

    /**
     * Creates the body element id for this controller a given action.
     *
     * @param string $unconsumed_path Unconsumed path to extract action from
     * @return string
     */
    protected function getBodyElementIdForControllerAndAction($unconsumed_path)
    {
        // Extract action from unconsumed path segment
        [$action] = $this->extract_action_and_args($unconsumed_path);

        // Extract controller name from class name
        $controller = preg_replace('/Controller$/', '', get_class($this));
        $controller = Trails_Inflector::underscore($controller);

        // Build main parts of the body element id
        $body_id_parts = explode('/', $controller);
        $body_id_parts[] = $action;

        // Create and set body element id
        $body_id = implode('-', $body_id_parts);

        return $body_id;
    }
}