Merge branch 'xorg/master' into xorg/f/xnet-accounts
[platal.git] / modules / marketing.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class MarketingModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'marketing' => $this->make_hook('marketing', AUTH_MDP, 'admin'),
28 'marketing/promo' => $this->make_hook('promo', AUTH_MDP, 'admin'),
29 'marketing/relance' => $this->make_hook('relance', AUTH_MDP, 'admin'),
30 'marketing/this_week' => $this->make_hook('week', AUTH_MDP, 'admin'),
31 'marketing/volontaire' => $this->make_hook('volontaire', AUTH_MDP, 'admin'),
32
33 'marketing/private' => $this->make_hook('private', AUTH_MDP, 'admin'),
34 'marketing/public' => $this->make_hook('public', AUTH_COOKIE),
35 'marketing/broken' => $this->make_hook('broken', AUTH_COOKIE),
36 );
37 }
38
39 function handler_marketing($page)
40 {
41 $page->changeTpl('marketing/index.tpl');
42 $page->setTitle('Marketing');
43
44 $alive = new UserFilter(new PFC_Not(new UFC_Dead()));
45 $registered = new UserFilter(new PFC_And(new UFC_Registered(), new PFC_Not(new UFC_Dead())));
46 $alive72 = new UserFilter(new PFC_And(new UFC_Promo('>=', UserFilter::GRADE_ING, 1972), new PFC_Not(new UFC_Dead())));
47 $registered72 = new UserFilter(new PFC_And(new UFC_Registered(), new UFC_Promo('>=', UserFilter::GRADE_ING, 1972), new PFC_Not(new UFC_Dead())));
48 $aliveWomen = new UserFilter(new PFC_And(new UFC_Sex(User::GENDER_FEMALE) , new PFC_Not(new UFC_Dead())));
49 $registeredWomen = new UserFilter(new PFC_And(new UFC_Registered(), new UFC_Sex(User::GENDER_FEMALE), new PFC_Not(new UFC_Dead())));
50 $statistics = array(
51 'alive' => $alive->getTotalCount(),
52 'registered' => $registered->getTotalCount(),
53 'alive72' => $alive72->getTotalCount(),
54 'registered72' => $registered72->getTotalCount(),
55 'womenAlive' => $aliveWomen->getTotalCount(),
56 'womenRegistered' => $registeredWomen->getTotalCount(),
57 );
58 $statistics['registeredRate'] = $statistics['registered'] / $statistics['alive'] * 100;
59 $statistics['registeredRate72'] = $statistics['registered72'] / $statistics['alive72'] * 100;
60 $statistics['womenRegisteredRate'] = $statistics['womenRegistered'] / $statistics['womenAlive'] * 100;
61
62 $registeredWeek = new UserFilter(new PFC_And(new UFC_Registered(false, '>=', strtotime('1 week ago')), new PFC_Not(new UFC_Dead())));
63 $registrationPending = XDB::fetchOneCell('SELECT COUNT(*)
64 FROM register_pending');
65 $registrations = array(
66 'week' => $registeredWeek->getTotalCount(),
67 'pending' => $registrationPending,
68 );
69
70 $ok = XDB::fetchOneCell('SELECT COUNT(*)
71 FROM register_mstats
72 WHERE success != \'0000-00-00\'');
73 $okWeek = XDB::fetchOneCell('SELECT COUNT(*)
74 FROM register_mstats
75 WHERE success >= {?}', strtotime('1 week ago'));
76 $res = XDB::fetchAllAssoc('SELECT type, COUNT(*) as count
77 FROM register_marketing
78 GROUP BY type');
79 $no = array();
80 foreach ($res as $value) {
81 $no[$value['type']] = $value['count'];
82 }
83 $no['week'] = XDB::fetchOneCell('SELECT COUNT(*)
84 FROM register_marketing
85 WHERE last >= {?}', strtotime('1 week ago'));
86 $marketings = array(
87 'ok' => $ok,
88 'okWeek' => $okWeek,
89 'noPerso' => (isset($no['user']) ? $no['user'] : 0),
90 'noXorg' => (isset($no['staff']) ? $no['staff'] : 0),
91 'noAX' => (isset($no['ax']) ? $no['ax'] : 0),
92 'noWeek' => $no['week'],
93 );
94
95 $page->assign('statistics', $statistics);
96 $page->assign('registrations', $registrations);
97 $page->assign('marketings', $marketings);
98 }
99
100 function handler_private($page, $hruid = null,
101 $action = null, $value = null)
102 {
103 global $globals;
104 $page->changeTpl('marketing/private.tpl');
105
106 $user = User::getSilent($hruid);
107 if (!$user) {
108 return PL_NOT_FOUND;
109 }
110
111 // Retrieves marketed user details.
112 if ($user->state != 'pending') {
113 $page->kill('Cet utilisateur est déjà inscrit');
114 }
115 if (!$user->hasProfile()) {
116 $page->kill('Cet utilisateur n\'est pas concerné par le marketing');
117 }
118 $matricule = $user->profile()->xorg_id;
119
120 $matricule_X = Profile::getSchoolId($matricule);
121
122 $page->assign('full_name', $user->fullName());
123 $page->assign('promo', $user->promo());
124 $page->assign('matricule', $matricule);
125 $page->assign('matricule_X',$matricule_X);
126
127 // Applies in-parameter action to the user.
128 if ($action == 'del') {
129 S::assert_xsrf_token();
130 Marketing::clear($user->id(), $value);
131 }
132
133 if ($action == 'rel') {
134 $market = Marketing::get($user->id(), $value);
135 if ($market == null) {
136 $page->trigWarning("Aucun marketing n'a été effectué vers $value");
137 } else {
138 $to = $market->user['to'];
139 $title = $market->getTitle();
140 $text = $market->getText();
141 $from = $market->sender_mail;
142 $page->assign('rel_from_user', $from);
143 $page->assign('rel_from_staff',
144 '"Equipe Polytechnique.org" <register@' . $globals->mail->domain . '>');
145 $page->assign('rel_to', $to);
146 $page->assign('rel_title', $title);
147 $page->assign('rel_text', $text);
148 $page->assign('rel_email', $value);
149 }
150 }
151
152 if ($action == 'relforce') {
153 S::assert_xsrf_token();
154
155 $market = Marketing::get($user->id(), Post::v('to'));
156 if (is_null($market)) {
157 $market = new Marketing($user->id(), Post::v('to'), 'default', null, 'staff');
158 }
159 $market->send(Post::v('title'), Post::v('message'));
160 $page->trigSuccess("Email envoyé");
161 }
162
163 if ($action == 'insrel') {
164 S::assert_xsrf_token();
165 if (Marketing::relance($user->id())) {
166 $page->trigSuccess('relance faite');
167 }
168 }
169
170 if ($action == 'add' && Post::has('email') && Post::has('type')) {
171 $market = new Marketing($user->id(), Post::v('email'), 'default', null, Post::v('type'), S::v('uid'));
172 $market->add(false);
173 }
174
175 // Retrieves and display the existing marketing attempts.
176 $res = XDB::iterator(
177 "SELECT r.*, s.email AS alias
178 FROM register_marketing AS r
179 LEFT JOIN email_source_account AS s ON (r.sender = s.uid AND s.type = 'forlife')
180 WHERE r.uid = {?}
181 ORDER BY date", $user->id());
182 $page->assign('addr', $res);
183
184 $res = XDB::query("SELECT date, relance FROM register_pending
185 WHERE uid = {?}", $user->id());
186 if (list($pending, $relance) = $res->fetchOneRow()) {
187 $page->assign('pending', $pending);
188 $page->assign('relance', $relance);
189 }
190
191 $page->assign('path', 'marketing/private/' . $user->login());
192 }
193
194 function handler_broken($page, $uid = null)
195 {
196 $page->changeTpl('marketing/broken.tpl');
197
198 if (is_null($uid)) {
199 return PL_NOT_FOUND;
200 }
201
202 $user = User::get($uid);
203 if (!$user) {
204 return PL_NOT_FOUND;
205 } elseif ($user->login() == S::user()->login()) {
206 pl_redirect('emails/redirect');
207 }
208
209 $res = XDB::query('SELECT p.deathdate IS NULL AS alive, r.last, IF(r.type = \'googleapps\', \'googleapps\', r.redirect) AS active_email
210 FROM accounts AS a
211 LEFT JOIN email_redirect_account AS r ON (a.uid = r.uid AND r.type IN (\'smtp\', \'googleapps\') AND r.flags = \'active\')
212 LEFT JOIN account_profiles AS ap ON (ap.uid = r.uid AND FIND_IN_SET(\'owner\', ap.perms))
213 LEFT JOIN profiles AS p ON (p.pid = ap.pid)
214 WHERE a.uid = {?}
215 ORDER BY r.broken_level, r.last',
216 $user->id());
217 if (!$res->numRows()) {
218 return PL_NOT_FOUND;
219 }
220 $user->addProperties($res->fetchOneAssoc());
221 $page->assign('user', $user);
222
223 $email = null;
224 require_once 'emails.inc.php';
225 if (Post::has('mail')) {
226 $email = valide_email(Post::v('mail'));
227 }
228 if (Post::has('valide') && isvalid_email_redirection($email)) {
229 S::assert_xsrf_token();
230
231 // security stuff
232 check_email($email, "Proposition d'une adresse surveillee pour " . $user->login() . " par " . S::user()->login());
233 $state = XDB::fetchOneCell('SELECT flags
234 FROM email_redirect_account
235 WHERE redirect = {?} AND uid = {?}',
236 $email, $user->id());
237 if ($state == 'broken') {
238 $page->trigWarning("L'adresse que tu as fournie est l'adresse actuelle de {$user->fullName()} et est en panne.");
239 } elseif ($state == 'active') {
240 $page->trigWarning("L'adresse que tu as fournie est l'adresse actuelle de {$user->fullName()}");
241 } elseif ($user->email && !Post::t('comment')) {
242 $page->trigError("Il faut que tu ajoutes un commentaire à ta proposition pour justifier le "
243 . "besoin de changer la redirection de {$user->fullName()}.");
244 } else {
245 $valid = new BrokenReq(S::user(), $user, $email, trim(Post::v('comment')));
246 $valid->submit();
247 $page->assign('sent', true);
248 }
249 } elseif ($email) {
250 $page->trigError("L'adresse proposée n'est pas une adresse acceptable pour une redirection.");
251 }
252 }
253
254 function handler_promo($page, $promo = null)
255 {
256 $page->changeTpl('marketing/promo.tpl');
257
258 if (is_null($promo)) {
259 $promo = S::v('promo', S::user()->promo());
260 }
261 $page->assign('promo', $promo);
262
263 $uf = new UserFilter(new PFC_And(new UFC_Promo('=', UserFilter::DISPLAY, $promo),
264 new PFC_Not(new UFC_Registered())),
265 array(new UFO_Name(Profile::LASTNAME), new UFO_Name(Profile::FIRSTNAME)));
266 $users = $uf->getUsers();
267 $page->assign('nonins', $users);
268 }
269
270 function handler_public($page, $hruid = null)
271 {
272 $page->changeTpl('marketing/public.tpl');
273
274 // Retrieves the user info, and checks the user is not yet registered.
275 $user = User::getSilent($hruid);
276 if (!$user || !$user->hasProfile()) {
277 return PL_NOT_FOUND;
278 }
279
280 if ($user->state != 'pending') {
281 $page->kill('Cet utilisateur est déjà inscrit');
282 }
283
284 // Displays the page, and handles the eventual user actions.
285 $page->assign('full_name', $user->fullName());
286 $page->assign('promo', $user->promo());
287
288 if (Post::has('valide')) {
289 S::assert_xsrf_token();
290 $email = trim(Post::v('mail'));
291
292 require_once 'emails.inc.php';
293 if (!isvalid_email_redirection($email)) {
294 $page->trigError('Email invalide&nbsp;!');
295 } else {
296 // On cherche les marketings précédents sur cette adresse
297 // email, en se restreignant au dernier mois
298
299 if (Marketing::get($user->id(), $email, true)) {
300 $page->assign('already', true);
301 } else {
302 $page->assign('ok', true);
303 check_email($email, "Une adresse surveillée est proposée au marketing par " . S::user()->login());
304 $market = new Marketing($user->id(), $email, 'default', null, Post::v('origine'), S::v('uid'),
305 Post::v('origine') == 'user' ? Post::v('personal_notes') : null);
306 $market->add();
307 }
308 }
309 } else {
310 global $globals;
311 require_once 'marketing.inc.php';
312
313 $sender = User::getSilent(S::v('uid'));
314 $perso_signature = 'Cordialement,<br />-- <br />' . $sender->fullName();
315 $market = new AnnuaireMarketing(null, true);
316 $text = $market->getText(array(
317 'sexe' => $user->isFemale(),
318 'forlife_email' => $user->forlifeEmail(),
319 'forlife_email2' => $user->forlifeEmailAlternate()
320 ));
321 $text = str_replace('%%hash%%', '', $text);
322 $text = str_replace('%%personal_notes%%', '<em id="personal_notes_display"></em>', $text);
323 $text = str_replace('%%sender%%',
324 '<span id="sender">' . $perso_signature . '</span>', $text);
325 $page->assign('text', nl2br($text));
326 $page->assign('perso_signature', $perso_signature);
327 $page->assign('mail_part', 'escaped_html');
328 }
329 }
330
331 function handler_week($page, $sorting = 'per_promo')
332 {
333 $page->changeTpl('marketing/this_week.tpl');
334
335 $sort = $sorting == 'per_promo' ? new UFO_Promo() : new UFO_Registration();
336
337 $uf = new UserFilter(new UFC_Registered(false, '>', strtotime('1 week ago')), $sort);
338 $page->assign('users', $uf->getUsers());
339 }
340
341 function handler_volontaire($page, $promo = null)
342 {
343 $page->changeTpl('marketing/volontaire.tpl');
344
345 $res = XDB::query(
346 'SELECT DISTINCT pd.promo
347 FROM register_marketing AS m
348 INNER JOIN account_profiles AS ap ON (m.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
349 INNER JOIN profile_display AS pd ON (pd.pid = ap.pid)
350 ORDER BY pd.promo');
351 $page->assign('promos', $res->fetchColumn());
352
353
354 if (!is_null($promo)) {
355 $it = XDB::iterator('SELECT m.uid, m.email, s.email AS forlife
356 FROM register_marketing AS m
357 INNER JOIN account_profiles AS ap ON (m.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
358 INNER JOIN profile_display AS pd ON (pd.pid = ap.pid)
359 LEFT JOIN email_source_account AS s ON (m.sender = s.uid AND s.type = \'forlife\')
360 WHERE pd.promo = {?}
361 ORDER BY pd.sort_name', $promo);
362 $page->assign('addr', $it);
363 }
364 }
365
366 function handler_relance($page)
367 {
368 $page->changeTpl('marketing/relance.tpl');
369
370 if (Post::has('relancer')) {
371 global $globals;
372 $nbdix = $globals->core->NbIns;
373
374 $sent = Array();
375 $users = User::getBulkUsersWithUIDs($_POST['relance']);
376 foreach ($users as $user) {
377 if ($tmp = Marketing::relance($user, $nbdix)) {
378 $sent[] = $tmp . ' a été relancé.';
379 }
380 }
381 $page->assign('sent', $sent);
382 }
383
384 $page->assign('relance', XDB::iterator('SELECT r.date, r.relance, r.uid
385 FROM register_pending AS r
386 WHERE hash != \'INSCRIT\'
387 ORDER BY date DESC'));
388 }
389 }
390
391 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
392 ?>