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