campaign.php 8.71 KB
Newer Older
1
<?php
2
namespace Controller;
3

Okhin's avatar
Okhin committed
4
5
6
use LQDN\Command\UserUpdateTotalCommand;
use LQDN\Command\UserCreateCommand;
use LQDN\Command\DonationCreateCommand;
7
use LQDN\Exception\InvalidEmailException;
Okhin's avatar
Okhin committed
8

9
10
11
12
13
14
15
16
17
18
19
class Campaign extends Controller
{
    /*
    Page principale du site
     */
    public static function show($f3, $args)
    {
        // Let's do some math first
        // So, get the $db
        $db = $f3->get('DB');
        // Number of month left for a one-year provisionning since CAMPAIGN_START_DATE
20
21
        $now = new \DateTime('now');
        $start = new \DateTime(CAMPAIGN_START_DATE);
22
23
24
25
26
27
28
29
30
        if ($start > $now) {
            $months = 0;
        } else {
            $months = $now->diff($start)->m;
        }
        $total_confirmed = 0;
        $total_provisional = 0;
        // So now, let's get the amount of confirmed dons, which are all the 1, 4, 101 and 102
        // statuses since CAMPAIGN_START_DATE
31
32
        $result = $db->query(
            "SELECT SUM(somme)
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
            AS total_confirmed
            FROM dons
            WHERE status IN (1, 4, 102)
                AND datec > '".CAMPAIGN_START_DATE."'"
            );
        $total_confirmed = intval($result->fetchColumn());
        $f3->set('total_confirmed', $total_confirmed);
        // Now, provisional. All reccuring pledge who have a datec in the last month (still active)
        // multiplied by the number of remaining month
        $result = $db->query("SELECT
            SUM(a.somme) AS total_provisional
            FROM (SELECT sum(somme) as somme
                FROM dons
                WHERE datec >= (CURRENT_DATE() - INTERVAL 1 MONTH)
                AND status IN (101, 102)
                GROUP BY identifier
            ) a");
        // How many month till the end of the year. Also, only 80% of them
        $total_provisional = intval($result->fetchColumn()) * (12 - $months);
        $f3->set('total_provisional', $total_provisional);
        // Now, let's calculate the percentage of each of them
        $campaign_goal = CAMPAIGN_BUDGET;
        $percent_confirmed = number_format($total_confirmed * 100 / $campaign_goal);
        $f3->set('percent_confirmed', $percent_confirmed);
        $percent_provisional = number_format($total_provisional * 100 / $campaign_goal);
        $f3->set('percent_provisional', $percent_provisional);
        $f3->set('block_content', 'campaign/home.html');
    }

    // Page d'attente
    public function wait($f3)
    {
65
        $f3->set('block_content', 'campaign/wait.html');
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
    }

    // FAQ donateurs
    public function faq($f3)
    {
        $f3->set('block_content', 'campaign/faq.html');
    }

    public function merci($f3)
    {
        $f3->set('form_visible', 'merci');
        $f3->set('block_content', 'campaign/home.html');
    }

    // Don
    public function donate($f3, $args)
    {
        // First, let's validate that all the required data exists
        $sum = $f3->get('amount');
        if ($f3->get('amount_other') != '') {
            $sum = $f3->get('amount_other');
        }

        $f3->set('amount', $sum);

        $status = 0;
        $f3->set('monthly', $f3->get('monthly'));
        if ($f3->get('monthly') == "true") {
            $status = 100;
        }

        $cumul_id = 0;
        $db = $f3->get('DB');
        // Si l'utilisateur est déjà connecté, on le récupère
        if ($f3->get('SESSION.user', true)) {
Okhin's avatar
Okhin committed
101
            $user = $f3->get('container')['user_finder']->findById($f3->get('SESSION.id'));
102
103
104
105
106
            $email = $user['email'];
            $user_id = $user['id'];
            $cumul_id = $user['cumul'];
        } else {
            // Depuis les dons cumulés, on recherche d'abord si le donateur existe déjà (basé sur son email)
107
            $email = \Utils::asl($f3->get('email'));
108
109
            $hash = hash('sha256', $f3->get('password'));

Okhin's avatar
Okhin committed
110
            $user = $f3->get('container')['user_finder']->findByEmail(\Utils::asl($email));
111

112
            if (is_array($user) && count($user) > 0) {
113
114
                // We have an existing user, we should try to login with the provided password
                // or 403.
115
                $mapper = new \DB\SQL\Mapper($f3->get('DB'), 'users');
116
117
118
                $auth = new \Auth($mapper, array('id' => 'email', 'pw' => 'hash'));
                $login = $auth->login($email, $hash);
                if (!$login) {
119
                    $f3->error(403);
120
                }
121
122
123
                $email = $user['email'];
                $user_id = $user['id'];
                $cumul_id = $user['cumul'];
124
125
            } else {
                // The user does not exist, so let's create it
126
127
128
129
130
131
132
                try {
                    $f3->get('container')['command_handler']->handle(new UserCreateCommand($email, $hash, $f3->get('pseudo'), 0, 0));
                } catch (InvalidEmailException $e) {
                    $f3->set("error", _("Email Invalide"));
                    $f3->error("403");
                }

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
                $user_id = $db->lastInsertId();
            }
        }
        $sql = "INSERT INTO dons SET
			status = '".$status."',
			datec  = NOW(),
			somme  = '".$sum."',
			user_id  = '".$user_id."',
			public = '".intval($f3->get('public'))."',
			cumul  = '".intval($cumul_id)."';";

        $db->query($sql);
        $id = $db->lastInsertId();
        if (!$id) {
            //TODO: Test this part
            @mail(SYSADMIN, 'LQDN Don, bug Mysql');
            $errno = 7;
        }
        setcookie("donlqdn", md5("SALT!!!".$id."!!!"), 86400, "/");

153
        $target = PAYMENT_URL; //"https://paiement.systempay.fr/vads-payment/";
154
        $transaction_date = new \DateTime('now', new \DateTimeZone("UTC"));
155
156
157
158
159
160
161
162
163
164
165
166
167
        $params = array(
            // Champs obligatoires
            "vads_trans_date" => $transaction_date->format("YmdHis"),
            "vads_site_id" => SITE_ID,
            "vads_action_mode" => "INTERACTIVE",
            "vads_ctx_mode" => CTX_MODE,
            // Autres codes possibles (page 16)
            "vads_trans_id" => str_repeat("0", 6-strlen($id)).$id,
            "vads_version" => "V2",
            // Champs facultatifs
            "vads_language" => $f3->get('lang'),
            "vads_order_id" => $id,
            "vads_url_cancel" => ROOTURL,
168
            "vads_url_check" => RETURN_CHECK_URL,
169
170
171
            "vads_url_error" => ROOTURL,
            "vads_url_referral" => ROOTURL,
            "vads_url_refused" => ROOTURL,
172
            "vads_url_return" => ROOTURL . "merci",
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
            "vads_url_success" => ROOTURL,
            "vads_validation_mode" => "0",
            "vads_shop_name" => "La Quadrature du Net",
            "vads_shop_url" => ROOTURL
        );
        if ($f3->get('monthly') == "true") {
            // En cas de paiement récurrent, on doit créer un compte carte si ce n'est pas déjà fait
            $identifier = "";
            $identifier = $id . "_" . substr($email, 0, strpos($email, '@'));
            $db->query("UPDATE dons SET identifier = '".$identifier."' WHERE id = '".$id."'");
            $db->query("INSERT INTO identifiers (identifier, user_id) VALUES ('". $identifier ."','" .$user_id ."')");
            $params["vads_identifier"] = substr($identifier, 0, 50); // Pas plus de 50 caractères
            $params["vads_page_action"] = "REGISTER_SUBSCRIBE";
            $params["vads_cust_email"] = $email; // Email du porteur
            $params["vads_sub_effect_date"] = date("Ymd"); // Date d'effet à ce jour
            $params["vads_sub_amount"] = $sum*100;
            $params["vads_sub_currency"] = "978";
            $params["vads_sub_desc"] = "RRULE:FREQ=MONTHLY;BYMONTHDAY=7"; // Tous les 7 du mois
        } else {
            // En cas de paiement ponctuel, le montant est donné différemment
            $params["vads_page_action"] = "PAYMENT";
            $params["vads_amount"] = $sum*100;
            $params["vads_currency"] = "978";
            $params["vads_payment_config"] = "SINGLE";
        }
        // Calcul de la signature
        ksort($params);
        $signature = "";
        foreach ($params as $key=>$value) {
            $signature .= $value."+";
        }
        $signature .= CERTIFICATE;
Guinness's avatar
Guinness committed
205
        $signature = base64_encode(hash_hmac('sha256', $signature, CERTIFICATE, true));
206
207
208
209
210
211
212
        $params["signature"] = $signature;

        $f3->set('target', $target);
        $f3->set('vads_params', $params);
        $f3->set('signature', $signature);

        // Log des informations envoyées pour debug en cas de souci
213
        $don_log = new \Log('dons.log');
214
215
216
217
218
        $don_log->write('target : '. $target);
        $don_log->write('params : ');
        foreach ($params as $key=>$value) {
            $don_log->write($key.' : '.$value);
        }
219
        $don_log->write('certificate : '. CERTIFICATE);
220
221
222
223
224
        $don_log->write('signature : '. $signature);
        $f3->set('form_visible', 'vads');
        Campaign::show($f3, $args);
    }
};