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

4 5 6 7
use LQDN\Command\UserUpdateTotalCommand;
use LQDN\Command\UserCreateCommand;
use LQDN\Command\DonationCreateCommand;

8 9 10 11 12 13 14 15 16 17 18
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
19 20
        $now = new \DateTime('now');
        $start = new \DateTime(CAMPAIGN_START_DATE);
21 22 23 24 25 26 27 28 29
        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
30 31
        $result = $db->query(
            "SELECT SUM(somme)
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
            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)
    {
64
        $f3->set('block_content', 'campaign/wait.html');
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
    }

    // 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)) {
100
            $user = $f3->get('container')['user_finder']->findById($f3->get('SESSION.id'));
101 102 103 104 105
            $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)
106
            $email = \Utils::asl($f3->get('email'));
107 108
            $hash = hash('sha256', $f3->get('password'));

109
            $user = $f3->get('container')['user_finder']->findByEmail(\Utils::asl($email));
110

111
            if (len($user) > 0) {
112 113
                // We have an existing user, we should try to login with the provided password
                // or 403.
114
                $mapper = new \DB\SQL\Mapper($f3->get('DB'), 'users');
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
                $auth = new \Auth($mapper, array('id' => 'email', 'pw' => 'hash'));
                $login = $auth->login($email, $hash);
                if (!$login) {
                    $f3->error(403);
                }
            } else {
                // The user does not exist, so let's create it
                $result = $db->query("INSERT INTO users (pseudo, email, hash)
					VALUES ('".$f3->get('pseudo')."', '$email', '$hash')");
                $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, "/");

144
        $target = PAYMENT_URL; //"https://paiement.systempay.fr/vads-payment/";
145
        $transaction_date = new \DateTime('now', new \DateTimeZone("UTC"));
146 147 148 149 150 151 152 153 154 155 156 157 158
        $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,
159
            "vads_url_check" => RETURN_CHECK_URL,
160 161 162
            "vads_url_error" => ROOTURL,
            "vads_url_referral" => ROOTURL,
            "vads_url_refused" => ROOTURL,
163
            "vads_url_return" => ROOTURL . "merci",
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
            "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;
196
        $signature = base64_encode(hash_hmac('sha256', $signature, CERTIFICATE, true));
197 198 199 200 201 202 203
        $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
204
        $don_log = new \Log('dons.log');
205 206 207 208 209
        $don_log->write('target : '. $target);
        $don_log->write('params : ');
        foreach ($params as $key=>$value) {
            $don_log->write($key.' : '.$value);
        }
210
        $don_log->write('certificate : '. CERTIFICATE);
211 212 213 214 215
        $don_log->write('signature : '. $signature);
        $f3->set('form_visible', 'vads');
        Campaign::show($f3, $args);
    }
};