Merge commit 'origin/master' into account
[platal.git] / modules / marketing.php
index 74ee081..bda1484 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2008 Polytechnique.org                              *
+ *  Copyright (C) 2003-2010 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -40,76 +40,46 @@ class MarketingModule extends PLModule
     {
         $page->changeTpl('marketing/index.tpl');
 
-        $page->setTitle('Polytechnique.org - Marketing');
-
-        // Quelques statistiques
-
-        $res   = XDB::query(
-                  "SELECT COUNT(*) AS vivants,
-                          COUNT(NULLIF(perms='admin' OR perms='user', 0)) AS inscrits,
-                          100*COUNT(NULLIF(perms='admin' OR perms='user', 0))/COUNT(*) AS ins_rate,
-                          COUNT(NULLIF(promo >= 1972, 0)) AS vivants72,
-                          COUNT(NULLIF(promo >= 1972 AND (perms='admin' OR perms='user'), 0)) AS inscrits72,
-                          100 * COUNT(NULLIF(promo >= 1972 AND (perms='admin' OR perms='user'), 0)) /
-                              COUNT(NULLIF(promo >= 1972, 0)) AS ins72_rate,
-                          COUNT(NULLIF(FIND_IN_SET('femme', flags), 0)) AS vivantes,
-                          COUNT(NULLIF(FIND_IN_SET('femme', flags) AND (perms='admin' OR perms='user'), 0)) AS inscrites,
-                          100 * COUNT(NULLIF(FIND_IN_SET('femme', flags) AND (perms='admin' OR perms='user'), 0)) /
-                              COUNT(NULLIF(FIND_IN_SET('femme', flags), 0)) AS inse_rate
-                     FROM auth_user_md5
-                    WHERE deces = 0");
-        $stats = $res->fetchOneAssoc();
-        $page->assign('stats', $stats);
-
-        $res   = XDB::query("SELECT count(*) FROM auth_user_md5 WHERE date_ins > ".
-                                      date('Ymd000000', strtotime('1 week ago')));
-        $page->assign('nbInsSem', $res->fetchOneCell());
-
-        $res = XDB::query("SELECT count(*) FROM register_pending WHERE hash != 'INSCRIT'");
-        $page->assign('nbInsEnCours', $res->fetchOneCell());
-
-        $res = XDB::query("SELECT count(*) FROM register_marketing");
-        $page->assign('nbInsMarket', $res->fetchOneCell());
-
-        $res = XDB::query("SELECT count(*) FROM register_mstats
-                                      WHERE TO_DAYS(NOW()) - TO_DAYS(success) <= 7");
-        $page->assign('nbInsMarkOK', $res->fetchOneCell());
+        $page->setTitle('Marketing');
+        $page->trigWarning("Les statistiques sont momentanéement désactivées");
     }
 
-    function handler_private(&$page, $uid = null,
+    function handler_private(&$page, $hruid = null,
                              $action = null, $value = null)
     {
         global $globals;
         $page->changeTpl('marketing/private.tpl');
 
-        if (is_null($uid)) {
+        $user = User::getSilent($hruid);
+        if (!$user) {
             return PL_NOT_FOUND;
         }
 
-        $page->assign('path', 'marketing/private/'.$uid);
+        // Retrieves marketed user details.
+        if ($user->state != 'pending') {
+            $page->kill('Cet utilisateur est déjà inscrit');
+        }
+        if (!$user->hasProfile()) {
+            $page->kill('Cet utilisateur n\'est pas concerné par le marketing');
+        }
+        $matricule = $user->profile()->xorg_id;
 
-        $res = XDB::query("SELECT  nom, prenom, promo, matricule
-                             FROM  auth_user_md5
-                            WHERE  user_id={?} AND perms='pending'", $uid);
+        require_once('user.func.inc.php');
+        $matricule_X = get_X_mat($matricule);
 
-        if (list($nom, $prenom, $promo, $matricule) = $res->fetchOneRow()) {
-            require_once('user.func.inc.php');
-            $matricule_X = get_X_mat($matricule);
-            $page->assign('nom', $nom);
-            $page->assign('prenom', $prenom);
-            $page->assign('promo', $promo);
-            $page->assign('matricule', $matricule);
-            $page->assign('matricule_X',$matricule_X);
-        } else {
-            $page->kill('uid invalide');
-        }
+        $page->assign('full_name', $user->fullName());
+        $page->assign('promo', $user->promo());
+        $page->assign('matricule', $matricule);
+        $page->assign('matricule_X',$matricule_X);
 
+        // Applies in-parameter action to the user.
         if ($action == 'del') {
-            Marketing::clear($uid, $value);
+            S::assert_xsrf_token();
+            Marketing::clear($user->id(), $value);
         }
 
         if ($action == 'rel') {
-            $market = Marketing::get($uid, $value);
+            $market = Marketing::get($user->id(), $value);
             if ($market == null) {
                 $page->trigWarning("Aucun marketing n'a été effectué vers $value");
             } else {
@@ -128,94 +98,101 @@ class MarketingModule extends PLModule
         }
 
         if ($action == 'relforce') {
-            $market = Marketing::get($uid, Post::v('to'));
+            S::assert_xsrf_token();
+
+            $market = Marketing::get($user->id(), Post::v('to'));
             if (is_null($market)) {
-                $market = new Marketing($uid, Post::v('to'), 'default', null, 'staff');
+                $market = new Marketing($user->id(), Post::v('to'), 'default', null, 'staff');
             }
             $market->send(Post::v('title'), Post::v('message'));
-            $page->trigSuccess("Mail envoyé");
+            $page->trigSuccess("Email envoyé");
         }
 
         if ($action == 'insrel') {
-            if (Marketing::relance($uid)) {
+            S::assert_xsrf_token();
+            if (Marketing::relance($user->id())) {
                 $page->trigSuccess('relance faite');
             }
         }
 
         if ($action == 'add' && Post::has('email') && Post::has('type')) {
-            $market = new Marketing($uid, Post::v('email'), 'default', null, Post::v('type'), S::v('uid'));
+            $market = new Marketing($user->id(), Post::v('email'), 'default', null, Post::v('type'), S::v('uid'));
             $market->add(false);
         }
 
+        // Retrieves and display the existing marketing attempts.
         $res = XDB::iterator(
                 "SELECT  r.*, a.alias
                    FROM  register_marketing AS r
-             INNER JOIN  aliases            AS a ON (r.sender=a.id AND a.type = 'a_vie')
+              LEFT JOIN  aliases            AS a ON (r.sender=a.id AND a.type = 'a_vie')
                   WHERE  uid={?}
-               ORDER BY  date", $uid);
+               ORDER BY  date", $user->id());
         $page->assign('addr', $res);
 
         $res = XDB::query("SELECT date, relance FROM register_pending
-                            WHERE uid = {?}", $uid);
+                            WHERE uid = {?}", $user->id());
         if (list($pending, $relance) = $res->fetchOneRow()) {
             $page->assign('pending', $pending);
             $page->assign('relance', $relance);
         }
+
+        $page->assign('path', 'marketing/private/' . $user->login());
     }
 
     function handler_broken(&$page, $uid = null)
     {
-        require_once('user.func.inc.php');
         $page->changeTpl('marketing/broken.tpl');
 
         if (is_null($uid)) {
             return PL_NOT_FOUND;
         }
-        $forlife = get_user_forlife($uid);
-        if (!$forlife) {
+
+        $user = User::get($uid);
+        if (!$user) {
             return PL_NOT_FOUND;
-        } elseif ($forlife == S::v('forlife')) {
+        } elseif ($user->login() == S::user()->login()) {
             pl_redirect('emails/redirect');
         }
 
-        $res = Xdb::query("SELECT  u.nom, u.prenom, u.promo, FIND_IN_SET('femme', u.flags) AS sexe,
-                                   u.deces = '0000-00-00' AS alive, a.alias AS forlife, b.alias AS bestalias,
-                                   IF(e.email IS NOT NULL, e.email, IF(FIND_IN_SET('googleapps', u.mail_storage), 'googleapps', NULL)) AS email, e.last
-                             FROM  auth_user_md5 AS u
-                       INNER JOIN  aliases       AS a ON (a.id = u.user_id AND a.type = 'a_vie')
-                       INNER JOIN  aliases       AS b ON (b.id = u.user_id AND FIND_IN_SET('bestalias', b.flags))
-                        LEFT JOIN  emails        AS e ON (e.flags = 'active' AND e.uid = u.user_id)
-                            WHERE  a.alias = {?}
-                         ORDER BY  e.panne_level, e.last", $forlife);
+        $res = XDB::query('SELECT  p.deathdate IS NULL AS alive, e.last,
+                                   IF(e.email IS NOT NULL, e.email,
+                                         IF(FIND_IN_SET(\'googleapps\', eo.storage), \'googleapps\', NULL)) AS email
+                             FROM  email_options AS eo
+                        LEFT JOIN  account_profiles AS ap ON (ap.uid = eo.uid AND FIND_IN_SET(\'owner\', ap.perms))
+                        LEFT JOIN  profiles AS p ON (p.pid = ap.pid)
+                        LEFT JOIN  emails        AS e ON (e.flags = \'active\' AND e.uid = eo.uid)
+                            WHERE  eo.uid = {?}
+                         ORDER BY  e.panne_level, e.last', $user->id());
         if (!$res->numRows()) {
             return PL_NOT_FOUND;
         }
-        $user = $res->fetchOneAssoc();
+        $user->addProperties($res->fetchOneAssoc());
         $page->assign('user', $user);
 
         $email = null;
+        require_once 'emails.inc.php';
         if (Post::has('mail')) {
-            require_once 'emails.inc.php';
             $email = valide_email(Post::v('mail'));
         }
         if (Post::has('valide') && isvalid_email_redirection($email)) {
+            S::assert_xsrf_token();
+
             // security stuff
-            check_email($email, "Proposition d'une adresse surveillee pour " . $user['forlife'] . " par " . S::v('forlife'));
-            $res = XDB::query("SELECT  e.flags
-                                 FROM  emails   AS e
-                           INNER JOIN  aliases  AS a ON (a.id = e.uid)
-                                WHERE  e.email = {?} AND a.alias = {?}", $email, $user['forlife']);
+            check_email($email, "Proposition d'une adresse surveillee pour " . $user->login() . " par " . S::user()->login());
+            $res = XDB::query("SELECT  flags
+                                 FROM  emails
+                                WHERE  email = {?} AND uid = {?}", $email, $user->id());
             $state = $res->numRows() ? $res->fetchOneCell() : null;
             if ($state == 'panne') {
-                $page->trigWarning("L'adresse que tu as fournie est l'adresse actuelle de {$user['prenom']} et est en panne.");
+                $page->trigWarning("L'adresse que tu as fournie est l'adresse actuelle de {$user->fullName()} et est en panne.");
             } elseif ($state == 'active') {
-                $page->trigWarning("L'adresse que tu as fournie est l'adresse actuelle de {$user['prenom']}");
-            } elseif ($user['email'] && !trim(Post::v('comment'))) {
+                $page->trigWarning("L'adresse que tu as fournie est l'adresse actuelle de {$user->fullName()}");
+            } elseif ($user->email && !trim(Post::v('comment'))) {
                 $page->trigError("Il faut que tu ajoutes un commentaire à ta proposition pour justifier le "
-                           ."besoin de changer la redirection de " . $user['prenom']);
+                               . "besoin de changer la redirection de {$user->fullName()}.");
             } else {
                 require_once 'validations.inc.php';
-                $valid = new BrokenReq(S::i('uid'), $user, $email, trim(Post::v('comment')));
+                $valid = new BrokenReq(S::user(), $user, $email, trim(Post::v('comment')));
                 $valid->submit();
                 $page->assign('sent', true);
             }
@@ -233,52 +210,71 @@ class MarketingModule extends PLModule
         }
         $page->assign('promo', $promo);
 
-        $sql = "SELECT  u.user_id, u.nom, u.prenom, u.last_known_email, u.matricule_ax,
-                        IF(MAX(m.last) > p.relance, MAX(m.last), p.relance) AS dern_rel, p.email
-                  FROM  auth_user_md5      AS u
-             LEFT JOIN  register_pending   AS p ON p.uid = u.user_id
-             LEFT JOIN  register_marketing AS m ON m.uid = u.user_id
-                 WHERE  u.promo = {?} AND u.deces = 0 AND u.perms='pending'
-              GROUP BY  u.user_id
-              ORDER BY  nom, prenom";
-        $page->assign('nonins', XDB::iterator($sql, $promo));
+        $uf = new UserFilter(new UFC_And(new UFC_Promo('=', UserFilter::DISPLAY, $promo),
+                                            new UFC_Not(new UFC_Registered())),
+                                array(new UFO_Name(UserFilter::LASTNAME), new UFO_Name(UserFilter::FIRSTNAME)));
+        $users = $uf->getUsers();
+        $page->assign('nonins', $users);
     }
 
-    function handler_public(&$page, $uid = null)
+    function handler_public(&$page, $hruid = null)
     {
         $page->changeTpl('marketing/public.tpl');
 
-        if (is_null($uid)) {
+        // Retrieves the user info, and checks the user is not yet registered.
+        $user = User::getSilent($hruid);
+        if (!$user || !$user->hasProfile()) {
             return PL_NOT_FOUND;
         }
 
-        $res = XDB::query("SELECT nom, prenom, promo FROM auth_user_md5
-                                      WHERE user_id={?} AND perms='pending'", $uid);
+        if ($user->state != 'pending') {
+            $page->kill('Cet utilisateur est déjà inscrit');
+        }
 
-        if (list($nom, $prenom, $promo) = $res->fetchOneRow()) {
-            $page->assign('prenom', $prenom);
-            $page->assign('nom', $nom);
-            $page->assign('promo', $promo);
+        // Displays the page, and handles the eventual user actions.
+        $page->assign('full_name', $user->fullName());
+        $page->assign('promo', $user->promo());
 
-            if (Post::has('valide')) {
-                $email = trim(Post::v('mail'));
+        if (Post::has('valide')) {
+            S::assert_xsrf_token();
+            $email = trim(Post::v('mail'));
 
-                if (!isvalid_email_redirection($email)) {
-                    $page->trigError("Email invalide !");
+            require_once 'emails.inc.php';
+            if (!isvalid_email_redirection($email)) {
+                $page->trigError('Email invalide&nbsp;!');
+            } else {
+                // On cherche les marketings précédents sur cette adresse
+                // email, en se restreignant au dernier mois
+
+                if (Marketing::get($user->id(), $email, true)) {
+                    $page->assign('already', true);
                 } else {
-                    // On cherche les marketings précédents sur cette adresse
-                    // email, en se restreignant au dernier mois
-
-                    if (Marketing::get($uid, $email, true)) {
-                        $page->assign('already', true);
-                    } else {
-                        $page->assign('ok', true);
-                        check_email($email, "Une adresse surveillée est proposée au marketing par " . S::v('forlife'));
-                        $market = new Marketing($uid, $email, 'default', null, Post::v('origine'), S::v('uid'));
-                        $market->add();
-                    }
+                    $page->assign('ok', true);
+                    check_email($email, "Une adresse surveillée est proposée au marketing par " . S::user()->login());
+                    $market = new Marketing($user->id(), $email, 'default', null, Post::v('origine'), S::v('uid'),
+                                            Post::v('origine') == 'user' ? Post::v('personal_notes') : null);
+                    $market->add();
                 }
             }
+        } else {
+            global $globals;
+            require_once 'marketing.inc.php';
+
+            $sender = User::getSilent(S::v('uid'));
+            $market = new AnnuaireMarketing(null, true);
+            $text = $market->getText(array(
+                'sexe'           => $user->isFemale(),
+                'forlife_email'  => $user->login() . '@' . $globals->mail->domain,
+                'forlife_email2' => $user->login() . '@' . $globals->mail->domain2
+            ));
+            $text = str_replace('%%hash%%', '', $text);
+            $text = str_replace('%%personal_notes%%', '<em id="personal_notes_display"></em>', $text);
+            $text = str_replace('%%sender%%',
+                                "<span id=\"sender\">" . $sender->fullName() . '</span>', $text);
+            $page->assign('text', nl2br($text));
+            // TODO (JAC): define a unique Xorg signature for all the emails we send.
+            $page->assign('xorg_signature', "L'équipe de Polytechnique.org,<br />Le portail des élèves & anciens élèves de l'École polytechnique");
+            $page->assign('perso_signature', $sender->fullName());
         }
     }
 
@@ -286,14 +282,10 @@ class MarketingModule extends PLModule
     {
         $page->changeTpl('marketing/this_week.tpl');
 
-        $sort = $sorting == 'per_promo' ? 'promo' : 'date_ins';
+        $sort = $sorting == 'per_promo' ? new UFO_Promo() : new UFO_Registration();
 
-        $sql = "SELECT  a.alias AS forlife, u.date_ins, u.promo, u.nom, u.prenom
-                  FROM  auth_user_md5  AS u
-            INNER JOIN  aliases        AS a ON (u.user_id = a.id AND a.type='a_vie')
-                 WHERE  u.date_ins > ".date("Ymd000000", strtotime ('1 week ago'))."
-              ORDER BY  u.$sort DESC";
-        $page->assign('ins', XDB::iterator($sql));
+        $uf = new UserFilter(new UFC_Registered(false, '>', strtotime('1 week ago')), $sort);
+        $page->assign('users', $uf->getUsers());
     }
 
     function handler_volontaire(&$page, $promo = null)
@@ -301,22 +293,21 @@ class MarketingModule extends PLModule
         $page->changeTpl('marketing/volontaire.tpl');
 
         $res = XDB::query(
-                "SELECT
-               DISTINCT  a.promo
+                'SELECT DISTINCT  pd.promo
                    FROM  register_marketing AS m
-             INNER JOIN  auth_user_md5      AS a  ON a.user_id = m.uid
-               ORDER BY  a.promo");
+             INNER JOIN  account_profiles AS ap ON (m.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
+             INNER JOIN  profile_display AS pd ON (pd.pid = ap.pid)
+               ORDER BY  pd.promo');
         $page->assign('promos', $res->fetchColumn());
 
 
         if (!is_null($promo)) {
-            $sql = "SELECT  a.nom, a.prenom, a.user_id,
-                            m.email, sa.alias AS forlife
-                      FROM  register_marketing AS m
-                INNER JOIN  auth_user_md5      AS a  ON a.user_id = m.uid AND a.promo = {?}
-                INNER JOIN  aliases            AS sa ON (m.sender = sa.id AND sa.type='a_vie')
-                  ORDER BY  a.nom";
-            $page->assign('addr', XDB::iterator($sql, $promo));
+            $it = XDB::iterator('SELECT  m.uid, m.email
+                                   FROM  register_marketing AS m
+                             INNER JOIN  account_profiles AS ap ON (m.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
+                             INNER JOIN  profile_display AS pd ON (pd.pid = ap.pid)
+                                  WHERE  pd.promo = {?}', $promo);
+            $page->assign('addr', $it);
         }
     }
 
@@ -325,24 +316,22 @@ class MarketingModule extends PLModule
         $page->changeTpl('marketing/relance.tpl');
 
         if (Post::has('relancer')) {
-            $res   = XDB::query("SELECT COUNT(*) FROM auth_user_md5 WHERE deces=0");
-            $nbdix = $res->fetchOneCell();
+            $nbdix = Marketing::getAliveUsersCount();
 
             $sent  = Array();
-            foreach (array_keys($_POST['relance']) as $uid) {
-                if ($tmp = Marketing::relance($uid, $nbdix)) {
-                    $sent[] = $tmp.' a été relancé';
+            $users = User::getBulkUsersWithUIDs($_POST['relance']);
+            foreach ($users as $user) {
+                if ($tmp = Marketing::relance($user, $nbdix)) {
+                    $sent[] = $tmp . ' a été relancé.';
                 }
             }
             $page->assign('sent', $sent);
         }
 
-        $sql = "SELECT  r.date, r.relance, r.uid, u.promo, u.nom, u.prenom
-                  FROM  register_pending AS r
-            INNER JOIN  auth_user_md5    AS u ON r. uid = u.user_id
-                 WHERE  hash!='INSCRIT'
-              ORDER BY  date DESC";
-        $page->assign('relance', XDB::iterator($sql));
+        $page->assign('relance', XDB::iterator('SELECT  r.date, r.relance, r.uid
+                                                  FROM  register_pending AS r
+                                                 WHERE  hash != \'INSCRIT\'
+                                              ORDER BY  date DESC'));
     }
 }