Moving to GitHub.
[platal.git] / modules / marketing.php
index 3d63d6d..a939a6a 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2009 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -24,27 +24,92 @@ class MarketingModule extends PLModule
     function handlers()
     {
         return array(
-            'marketing'            => $this->make_hook('marketing',  AUTH_MDP, 'admin'),
-            'marketing/promo'      => $this->make_hook('promo',      AUTH_MDP, 'admin'),
-            'marketing/relance'    => $this->make_hook('relance',    AUTH_MDP, 'admin'),
-            'marketing/this_week'  => $this->make_hook('week',       AUTH_MDP, 'admin'),
-            'marketing/volontaire' => $this->make_hook('volontaire', AUTH_MDP, 'admin'),
-
-            'marketing/private'    => $this->make_hook('private',    AUTH_MDP, 'admin'),
-            'marketing/public'     => $this->make_hook('public',     AUTH_COOKIE),
-            'marketing/broken'     => $this->make_hook('broken',     AUTH_COOKIE),
+            'marketing'            => $this->make_hook('marketing',  AUTH_PASSWD, 'admin'),
+            'marketing/promo'      => $this->make_hook('promo',      AUTH_PASSWD, 'admin'),
+            'marketing/relance'    => $this->make_hook('relance',    AUTH_PASSWD, 'admin'),
+            'marketing/this_week'  => $this->make_hook('week',       AUTH_PASSWD, 'admin'),
+            'marketing/volontaire' => $this->make_hook('volontaire', AUTH_PASSWD, 'admin'),
+
+            'marketing/private'    => $this->make_hook('private',    AUTH_PASSWD, 'admin'),
+            'marketing/public'     => $this->make_hook('public',     AUTH_COOKIE, 'user'),
+            'marketing/broken'     => $this->make_hook('broken',     AUTH_COOKIE, 'user'),
         );
     }
 
-    function handler_marketing(&$page)
+    function handler_marketing($page)
     {
         $page->changeTpl('marketing/index.tpl');
-
         $page->setTitle('Marketing');
-        $page->trigWarning("Les statistiques sont momentanéement désactivées");
+
+        $alive = array(
+            'all'    => new ProfileFilter(new PFC_Not(new UFC_Dead())),
+            'women'  => new ProfileFilter(new PFC_And(new UFC_Sex(User::GENDER_FEMALE) , new PFC_Not(new UFC_Dead()))),
+            'x'      => new ProfileFilter(new PFC_And(new PFC_Not(new UFC_Dead()), new UFC_AccountType('x'))),
+            '72'     => new ProfileFilter(new PFC_And(new UFC_Promo('>=', UserFilter::GRADE_ING, 1972), new PFC_Not(new UFC_Dead()))),
+            'master' => new ProfileFilter(new PFC_And(new PFC_Not(new UFC_Dead()), new UFC_AccountType('master'))),
+            'phd'    => new ProfileFilter(new PFC_And(new PFC_Not(new UFC_Dead()), new UFC_AccountType('phd')))
+        );
+        $registered = array(
+            'all'    => new ProfileFilter(new PFC_And(new UFC_Registered(true), new PFC_Not(new UFC_Dead()))),
+            'women'  => new ProfileFilter(new PFC_And(new UFC_Registered(true), new UFC_Sex(User::GENDER_FEMALE), new PFC_Not(new UFC_Dead()))),
+            'x'      => new ProfileFilter(new PFC_And(new UFC_Registered(true), new PFC_Not(new UFC_Dead()), new UFC_AccountType('x'))),
+            '72'     => new ProfileFilter(new PFC_And(new UFC_Registered(true), new UFC_Promo('>=', UserFilter::GRADE_ING, 1972), new PFC_Not(new UFC_Dead()))),
+            'master' => new ProfileFilter(new PFC_And(new UFC_Registered(true), new PFC_Not(new UFC_Dead()), new UFC_AccountType('master'))),
+            'phd'    => new ProfileFilter(new PFC_And(new UFC_Registered(true), new PFC_Not(new UFC_Dead()), new UFC_AccountType('phd')))
+        );
+        $statistics = array(
+            'all'    => array('description' => "Étudiants et anciens de l'X"),
+            'women'  => array('description' => "Étudiantes et anciennes de l'X"),
+            'x'      => array('description' => 'X'),
+            '72'     => array('description' => 'X vivants depuis la promo 1972'),
+            'master' => array('description' => "Masters de l'X"),
+            'phd'    => array('description' => "Docteurs de l'X")
+        );
+        foreach ($statistics as $key => &$data) {
+            $data['alive'] = $alive[$key]->getTotalCount();
+            $data['registered'] = $registered[$key]->getTotalCount();
+            $data['rate'] = round($data['registered'] / $data['alive'] * 100, 2);
+        }
+
+        $registeredWeek = new ProfileFilter(new PFC_And(new UFC_Registered(true, '>=', strtotime('1 week ago')), new PFC_Not(new UFC_Dead())));
+        $registrationPending = XDB::fetchOneCell('SELECT  COUNT(*)
+                                                    FROM  register_pending');
+        $registrations = array(
+            'week'    => $registeredWeek->getTotalCount(),
+            'pending' => $registrationPending,
+        );
+
+        $ok = XDB::fetchOneCell('SELECT  COUNT(*)
+                                   FROM  register_mstats
+                                  WHERE  success != \'0000-00-00\'');
+        $okWeek = XDB::fetchOneCell('SELECT  COUNT(*)
+                                       FROM  register_mstats
+                                      WHERE  success >= {?}', strtotime('1 week ago'));
+        $res = XDB::fetchAllAssoc('SELECT  type, COUNT(*) as count
+                                     FROM  register_marketing
+                                 GROUP BY  type');
+        $no = array();
+        foreach ($res as $value) {
+            $no[$value['type']] = $value['count'];
+        }
+        $no['week'] = XDB::fetchOneCell('SELECT  COUNT(*)
+                                           FROM  register_marketing
+                                          WHERE  last >= {?}', strtotime('1 week ago'));
+        $marketings = array(
+            'ok'      => $ok,
+            'okWeek'  => $okWeek,
+            'noPerso' => (isset($no['user']) ? $no['user'] : 0),
+            'noXorg'  => (isset($no['staff']) ? $no['staff'] : 0),
+            'noAX'    => (isset($no['ax']) ? $no['ax'] : 0),
+            'noWeek'  => $no['week'],
+        );
+
+        $page->assign('statistics', $statistics);
+        $page->assign('registrations', $registrations);
+        $page->assign('marketings', $marketings);
     }
 
-    function handler_private(&$page, $hruid = null,
+    function handler_private($page, $hruid = null,
                              $action = null, $value = null)
     {
         global $globals;
@@ -64,8 +129,7 @@ class MarketingModule extends PLModule
         }
         $matricule = $user->profile()->xorg_id;
 
-        require_once('user.func.inc.php');
-        $matricule_X = get_X_mat($matricule);
+        $matricule_X = Profile::getSchoolId($matricule);
 
         $page->assign('full_name', $user->fullName());
         $page->assign('promo', $user->promo());
@@ -122,10 +186,10 @@ class MarketingModule extends PLModule
 
         // Retrieves and display the existing marketing attempts.
         $res = XDB::iterator(
-                "SELECT  r.*, a.alias
-                   FROM  register_marketing AS r
-              LEFT JOIN  aliases            AS a ON (r.sender=a.id AND a.type = 'a_vie')
-                  WHERE  uid={?}
+                "SELECT  r.*, s.email AS alias
+                   FROM  register_marketing   AS r
+              LEFT JOIN  email_source_account AS s ON (r.sender = s.uid AND s.type = 'forlife')
+                  WHERE  r.uid = {?}
                ORDER BY  date", $user->id());
         $page->assign('addr', $res);
 
@@ -139,7 +203,7 @@ class MarketingModule extends PLModule
         $page->assign('path', 'marketing/private/' . $user->login());
     }
 
-    function handler_broken(&$page, $uid = null)
+    function handler_broken($page, $uid = null)
     {
         $page->changeTpl('marketing/broken.tpl');
 
@@ -154,15 +218,14 @@ class MarketingModule extends PLModule
             pl_redirect('emails/redirect');
         }
 
-        $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());
+        $res = XDB::query('SELECT  p.deathdate IS NULL AS alive, r.last, IF(r.type = \'googleapps\', \'googleapps\', r.redirect) AS active_email
+                             FROM  accounts               AS a
+                        LEFT JOIN  email_redirect_account AS r  ON (a.uid = r.uid AND r.type IN (\'smtp\', \'googleapps\') AND r.flags = \'active\')
+                        LEFT JOIN  account_profiles       AS ap ON (ap.uid = r.uid AND FIND_IN_SET(\'owner\', ap.perms))
+                        LEFT JOIN  profiles               AS p  ON (p.pid = ap.pid)
+                            WHERE  a.uid = {?}
+                         ORDER BY  r.broken_level, r.last',
+                          $user->id());
         if (!$res->numRows()) {
             return PL_NOT_FOUND;
         }
@@ -174,50 +237,50 @@ class MarketingModule extends PLModule
         if (Post::has('mail')) {
             $email = valide_email(Post::v('mail'));
         }
-        if (Post::has('valide') && isvalid_email_redirection($email)) {
+        if (Post::has('valide') && isvalid_email_redirection($email, $user)) {
             S::assert_xsrf_token();
 
             // security stuff
             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') {
+            $state = XDB::fetchOneCell('SELECT  flags
+                                          FROM  email_redirect_account
+                                         WHERE  redirect = {?} AND uid = {?}',
+                                       $email, $user->id());
+            if ($state == 'broken') {
                 $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->fullName()}");
-            } elseif ($user->email && !trim(Post::v('comment'))) {
+            } elseif ($user->email && !Post::t('comment')) {
                 $page->trigError("Il faut que tu ajoutes un commentaire à ta proposition pour justifier le "
                                . "besoin de changer la redirection de {$user->fullName()}.");
             } else {
-                require_once 'validations.inc.php';
                 $valid = new BrokenReq(S::user(), $user, $email, trim(Post::v('comment')));
                 $valid->submit();
                 $page->assign('sent', true);
             }
         } elseif ($email) {
-            $page->trigError("L'adresse proposée n'est pas une adresse acceptable pour une redirection");
+            $page->trigError("L'adresse proposée n'est pas une adresse acceptable pour une redirection.");
         }
     }
 
-    function handler_promo(&$page, $promo = null)
+    function handler_promo($page, $promo = null)
     {
         $page->changeTpl('marketing/promo.tpl');
 
         if (is_null($promo)) {
-            $promo = S::v('promo');
+            $promo = S::v('promo', S::user()->promo());
         }
         $page->assign('promo', $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)));
+        $uf = new UserFilter(new PFC_And(new UFC_Promo('=', UserFilter::DISPLAY, $promo),
+                                         new PFC_Not(new UFC_Registered()),
+                                         new PFC_Not(new UFC_Dead())),
+                             array(new UFO_Name()));
         $users = $uf->getUsers();
         $page->assign('nonins', $users);
     }
 
-    function handler_public(&$page, $hruid = null)
+    function handler_public($page, $hruid = null)
     {
         $page->changeTpl('marketing/public.tpl');
 
@@ -240,7 +303,7 @@ class MarketingModule extends PLModule
             $email = trim(Post::v('mail'));
 
             require_once 'emails.inc.php';
-            if (!isvalid_email_redirection($email)) {
+            if (!isvalid_email_redirection($email, $user)) {
                 $page->trigError('Email invalide&nbsp;!');
             } else {
                 // On cherche les marketings précédents sur cette adresse
@@ -261,24 +324,24 @@ class MarketingModule extends PLModule
             require_once 'marketing.inc.php';
 
             $sender = User::getSilent(S::v('uid'));
+            $perso_signature = 'Cordialement,<br />-- <br />' . $sender->fullName();
             $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
+                'forlife_email'  => $user->hruid . "@" . $user->mainEmailDomain(),
+                'forlife_email2' => $user->hruid . "@" . $user->alternateEmailDomain()
             ));
             $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);
+                                '<span id="sender">' . $perso_signature . '</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());
+            $page->assign('perso_signature', $perso_signature);
+            $page->assign('mail_part', 'escaped_html');
         }
     }
 
-    function handler_week(&$page, $sorting = 'per_promo')
+    function handler_week($page, $sorting = 'per_promo')
     {
         $page->changeTpl('marketing/this_week.tpl');
 
@@ -288,7 +351,7 @@ class MarketingModule extends PLModule
         $page->assign('users', $uf->getUsers());
     }
 
-    function handler_volontaire(&$page, $promo = null)
+    function handler_volontaire($page, $promo = null)
     {
         $page->changeTpl('marketing/volontaire.tpl');
 
@@ -302,21 +365,24 @@ class MarketingModule extends PLModule
 
 
         if (!is_null($promo)) {
-            $it = XDB::iterator('SELECT  m.uid, m.email
+            $it = XDB::iterator('SELECT  m.uid, m.email, s.email AS forlife
                                    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);
+                              LEFT JOIN  email_source_account AS s ON (m.sender = s.uid AND s.type = \'forlife\')
+                                  WHERE  pd.promo = {?}
+                               ORDER BY  pd.sort_name', $promo);
             $page->assign('addr', $it);
         }
     }
 
-    function handler_relance(&$page)
+    function handler_relance($page)
     {
         $page->changeTpl('marketing/relance.tpl');
 
         if (Post::has('relancer')) {
-            $nbdix = Marketing::getAliveUsersCount();
+            global $globals;
+            $nbdix = $globals->core->NbIns;
 
             $sent  = Array();
             $users = User::getBulkUsersWithUIDs($_POST['relance']);
@@ -335,5 +401,5 @@ class MarketingModule extends PLModule
     }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
 ?>