aboutsummaryrefslogtreecommitdiff
path: root/app/class/Controller.php
blob: 2b389880005b0ab03e509efc29af4755c51b7828 (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
<?php

namespace Wcms;

use DateTime;
use DateTimeImmutable;
use Exception;
use InvalidArgumentException;
use League\Plates\Engine;
use Throwable;

class Controller
{
    /** @var Session */
    protected $session;

    /** @var User */
    protected $user;

    /** @var \AltoRouter */
    protected $router;

    /** @var Modeluser */
    protected $usermanager;

    /** @var Modelpage */
    protected $pagemanager;

    protected $plates;
    
    /** @var DateTimeImmutable */
    protected $now;

    public function __construct($router)
    {
        $this->session = new Session($_SESSION['user' . Config::basepath()] ?? []);
        $this->usermanager = new Modeluser();

        $this->setuser();
        $this->router = $router;
        $this->pagemanager = new Modelpage();
        $this->initplates();
        $this->now = new DateTimeImmutable("now", timezone_open("Europe/Paris"));
    }

    public function setuser()
    {
        // check session, then cookies
        if (!empty($this->session->user)) {
            $user = $this->usermanager->get($this->session->user);
        } elseif (!empty($_COOKIE['authtoken'])) {
            try {
                $modelconnect = new Modelconnect();
                $datas = $modelconnect->checkcookie();
                $user = $this->usermanager->get($datas['userid']);
                if ($user !== false && $user->checksession($datas['wsession'])) {
                    $this->session->addtosession("wsession", $datas['wsession']);
                    $this->session->addtosession("user", $datas['userid']);
                } else {
                    $user = false;
                }
            } catch (Exception $e) {
                Model::sendflashmessage("Invalid Autentification cookie exist : $e", "warning");
            }
        }
        // create visitor
        if (empty($user)) {
            $this->user = new User();
        } else {
            $this->user = $user;
        }
    }

    public function initplates()
    {
        $router = $this->router;
        $this->plates = new Engine(Model::TEMPLATES_DIR);
        $this->plates->registerFunction('url', function (string $string, array $vars = [], string $get = '') {
            return $this->generate($string, $vars, $get);
        });
        $this->plates->registerFunction('upage', function (string $string, string $id) {
            return $this->generate($string, ['page' => $id]);
        });
        $this->plates->addData(['flashmessages' => Model::getflashmessages()]);
    }

    public function showtemplate($template, $params)
    {
        $params = array_merge($this->commonsparams(), $params);
        echo $this->plates->render($template, $params);
    }

    public function commonsparams()
    {
        $commonsparams = [];
        $commonsparams['router'] = $this->router;
        $commonsparams['user'] = $this->user;
        $commonsparams['pagelist'] = $this->pagemanager->list();
        $commonsparams['css'] = Model::assetscsspath();
        $commonsparams['now'] = new DateTimeImmutable();
        return $commonsparams;
    }



    /**
     * Generate the URL for a named route. Replace regexes with supplied parameters.
     *
     * @param string $route The name of the route.
     * @param array $params Associative array of parameters to replace placeholders with.
     * @param string $get Optionnal query GET parameters formated
     * @return string The URL of the route with named parameters in place.
     * @throws InvalidArgumentException If the route does not exist.
     */
    public function generate(string $route, array $params = [], string $get = ''): string
    {
        try {
            return $this->router->generate($route, $params) . $get;
        } catch (Exception $e) {
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
        }
    }

    public function redirect($url)
    {
        header('Location: ' . $url);
        exit;
    }

    public function routedirect(string $route, array $vars = [])
    {
        $this->redirect($this->generate($route, $vars));
    }

    public function routedirectget(string $route, array $vars = [])
    {
        $get = '?';
        foreach ($vars as $key => $value) {
            $get .= $key . '=' . $value . '&';
        }
        $get = rtrim($get, '&');
        $this->redirect($this->generate($route, []) . $get);
    }

    public function error(int $code)
    {
        http_response_code($code);
        exit;
    }

    /**
     *
     */
    public function sendstatflashmessage(int $count, int $total, string $message)
    {
        if ($count === $total) {
            Model::sendflashmessage($count . ' / ' . $total . ' ' . $message, 'success');
        } elseif ($count > 0) {
            Model::sendflashmessage($count . ' / ' . $total . ' ' . $message, 'warning');
        } else {
            Model::sendflashmessage($count . ' / ' . $total . ' ' . $message, 'error');
        }
    }

    /**
     * Destroy session and cookie token in user database
     */
    public function disconnect()
    {
        $this->session->addtosession('user', '');
        $this->user->destroysession($this->session->wsession);
        $this->session->addtosession('wsession', '');
        $this->usermanager->add($this->user);

    }
}